Skip to content

Commit 1708cc2

Browse files
author
王鹏
committed
feat(EASY): add LCP_2_fraction
1 parent 991200a commit 1708cc2

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package pp.arithmetic.LCP;
2+
3+
import pp.arithmetic.Util;
4+
5+
/**
6+
* Created by wangpeng on 2019-09-30.
7+
* LCP 2. 分式化简
8+
* <p>
9+
* 有一个同学在学习分式。他需要将一个连分数化成最简分数,你能帮助他吗?
10+
* <p>
11+
* https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/09/09/fraction_example_1.jpg
12+
* <p>
13+
* 连分数是形如上图的分式。在本题中,所有系数都是大于等于0的整数。
14+
* <p>
15+
*  
16+
* <p>
17+
* 输入的cont代表连分数的系数(cont[0]代表上图的a0,以此类推)。返回一个长度为2的数组[n, m],使得连分数的值等于n / m,且n, m最大公约数为1。
18+
* <p>
19+
*  
20+
* <p>
21+
* 示例 1:
22+
* <p>
23+
* 输入:cont = [3, 2, 0, 2]
24+
* 输出:[13, 4]
25+
* 解释:原连分数等价于3 + (1 / (2 + (1 / (0 + 1 / 2))))。注意[26, 8], [-13, -4]都不是正确答案。
26+
* 示例 2:
27+
* <p>
28+
* 输入:cont = [0, 0, 3]
29+
* 输出:[3, 1]
30+
* 解释:如果答案是整数,令分母为1即可。
31+
* 限制:
32+
* <p>
33+
* cont[i] >= 0
34+
* 1 <= cont的长度 <= 10
35+
* cont最后一个元素不等于0
36+
* 答案的n, m的取值都能被32位int整型存下(即不超过2 ^ 31 - 1)。
37+
* <p>
38+
* 来源:力扣(LeetCode)
39+
* 链接:https://leetcode-cn.com/problems/deep-dark-fraction
40+
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
41+
*/
42+
public class _2_fraction {
43+
44+
public static void main(String[] args) {
45+
_2_fraction fraction = new _2_fraction();
46+
Util.printArray(fraction.fraction(new int[]{3, 2, 0, 2}));
47+
Util.printArray(fraction.fraction(new int[]{0, 0, 3}));
48+
Util.printArray(fraction.fraction(new int[]{3}));
49+
}
50+
51+
/**
52+
* 解题思路:
53+
* 对整个题目比划比划你会发现,整个解题的过程就是个循环求解分式,为了更好的写代码,逆向求解
54+
* 1、定义一个length为2的数组result,第一位是分子,第二位是分母
55+
* 2、逆向遍历数组
56+
* 3、对于第一位,result[0]=1,result[1]=item
57+
* 4、分式对下一位相加,直接分母*该值加到分子上,并将分子分母求导数
58+
* 5、由于是逆向求解,还需要对最终结果进行求导数
59+
*
60+
* @param cont
61+
* @return
62+
*/
63+
public int[] fraction(int[] cont) {
64+
//1
65+
int[] result = new int[2];
66+
//2
67+
for (int i = cont.length - 1; i >= 0; i--) {
68+
int item = cont[i];
69+
if (result[0] == 0 && result[1] == 0) {
70+
//3
71+
result[0] = 1;
72+
result[1] = item;
73+
} else {
74+
//4
75+
result[0] += result[1] * item;
76+
swap(result);
77+
}
78+
}
79+
//5
80+
swap(result);
81+
return result;
82+
}
83+
84+
private void swap(int[] arr) {
85+
int temp = arr[0];
86+
arr[0] = arr[1];
87+
arr[1] = temp;
88+
}
89+
}

0 commit comments

Comments
 (0)