codewars Twice linear
去重加保序的集合
import java.util.SortedSet;
import java.util.TreeSet;
public class DoubleLinear {
public static int dblLinear1(int n) {
if (n == 0)
return 1;
// creat a sorted list (always sorted)
SortedSet<Integer> resultList = new TreeSet<Integer>();
// Codewar condition u(0)=1
resultList.add(1);
for (int i = 0; i < n; i++) {
// get the first element of our treeset
int firstElement = resultList.first();
resultList.add(firstElement * 2 + 1);
resultList.add(firstElement * 3 + 1);
resultList.remove(firstElement);
}
return resultList.first();
}
}
y和z可以理解为都需要向前进,走的慢的人先走
public static int dblLinear(int n) {
int[] nums = new int[n + 1];
nums[0] = 1;
int i = 0, j = 0, k = 1;
while (k < n + 1) {
int y = 2 * nums[i] + 1;
int z = 3 * nums[j] + 1;
if (y < z) {
nums[k++] = y;
i++;
} else if (z < y) {
nums[k++] = z;
j++;
} else {
nums[k++] = z;
i++;
j++;
}
}
return nums[n];
}