Sum Target in Array - Google Interview
给一个array 和一个 target求出 array里有几组tuple相加是小于等于target的。 第二题是一个array里面只有0-9的digits, 有一个target, 判断是否存在一种组合可以等于target。eg: [6,3,1,0,5] target=78,这个return True. 63+10+5 = 78 如果target= 636 return True. 631+0+5 = 636
给一个array 和一个 target求出 array里有几组tuple相加是小于等于target的。 第二题是一个array里面只有0-9的digits, 有一个target, 判断是否存在一种组合可以等于target。eg: [6,3,1,0,5] target=78,这个return True. 63+10+5 = 78 如果target= 636 return True. 631+0+5 = 636
public int tupletLessThan(int[] array, int target) {
Arrays.sort(array);
int count;
for (int i=0; i<array.length-2; i++) {
int start = i+1;
int end = array.length-1;
//fix end, and add all the numbers that sums to less than target
while(start < end) {
while (array[start] + array[end] + array[i] < target) {
count++;
start++;
}
end–;
start = i+1;
}
}
return count;
}
Arrays.sort(array);
int count;
for (int i=0; i<array.length-2; i++) {
int start = i+1;
int end = array.length-1;
//fix end, and add all the numbers that sums to less than target
while(start < end) {
while (array[start] + array[end] + array[i] < target) {
count++;
start++;
}
end–;
start = i+1;
}
}
return count;
}
public boolean findTarget(int[] array, int target) {
int curr = 0;
}
int curr = 0;
}
private boolean helper(int[] array, int target, int start) {
if (target < 0) {
return false;
}
if (start == array.length) {
return target == 0;
}
for (int i=start; i<array.length; i++) {
int r = generateNumber(array, start, i);
if (helper, array, target-r, i+1) {
return true;
}
}
return false;
}
if (target < 0) {
return false;
}
if (start == array.length) {
return target == 0;
}
for (int i=start; i<array.length; i++) {
int r = generateNumber(array, start, i);
if (helper, array, target-r, i+1) {
return true;
}
}
return false;
}
private int generateNumber(int[] arr, int start, int end) {
int res = 0;
for (int i=start; i<=end; i++) {
res *= 10;
res += arr[i];
}
return res;
}
int res = 0;
for (int i=start; i<=end; i++) {
res *= 10;
res += arr[i];
}
return res;
}