标签:arch href binary top 方法 java 三元 pointer 错误
topic:ThreeSum
目标:用于统计一个数组中和为 0 的三元组数量,每个三元组都不重复
public class ThreeSumSlow implements ThreeSum{
@Override
public int count(int[] shuzu) {
int c = 0; //次数
for(int i = 0; i < shuzu.length - 2; i++) {
for(int j = i + 1; j < shuzu.length - 1; j++) {
for(int z = j + 1; z < shuzu.length; z++) {
if(shuzu[i]+shuzu[j]+shuzu[z] == 0) c++;
}
}
}
return c;
}
}
注意:数组中不能有重复元素
import java.util.Arrays;
public class ThreeSumBinarySearch implements ThreeSum{
@Override
public int count(int[] shuzu) {
//先排序
Arrays.sort(shuzu);
int len = shuzu.length;
int c = 0;
int negSum;
int index; //找到的相反数的下标
//先对两个元素求和,再找有没有和的相反数的数
for(int i = 0; i < len - 1; i++) {
for(int j = i + 1; j < len; j++) {
negSum = - shuzu[i] - shuzu[j];
index = BinarySearch.binarySearch(shuzu, negSum);
if(index > j) c ++; //如果小于j,可能会重复计数!!!
}
}
return c;
}
}
import java.util.Arrays;
public class ThreeSumTwoPointer {
//先将数组排序,再设置双指针查找
public int count(int[] shuzu) {
Arrays.sort(shuzu);
int N = shuzu.length;
int c = 0; //count
for(int i = 0; i < N - 2; i++) {
if(i > 0 && shuzu[i] == shuzu[i-1]) continue; //若该数与上一个index的数相同,则跳过。因为已经考虑过这种情况了
int l = i+1;
int r = N-1;
int target = -shuzu[i];
while(l<r) {
int number = shuzu[l] + shuzu[r];
if(number == target) {
c++;
while(l<r && shuzu[l] == shuzu[l+1]) l++;
while(l<r && shuzu[r] == shuzu[r-1]) r--;
l++;
r--;
}
else if(number < target) l++; //为什么这里不需要判别与后面的数一样与否,应该就算一样,c也不会再错误地多算一次,因为加起来肯定与target不一样
else r--;
}
}
return c;
}
}
标签:arch href binary top 方法 java 三元 pointer 错误
原文地址:https://www.cnblogs.com/Cindy-H/p/13635063.html