今天又碰到一个问题,
我认为它是很经典的效率优化问题,在我写注释的地方,假如不加上这一段,在输入数组为
[0,0,0,0]时它的效率会拖到920ms,但是加上后会缩小到40ms.
效率优化了20倍;
这里的主要作用就是去重。
有人会问外面一层也有过判断啊,这里是因为在循环里会一直循环下去,进行的还是无效循环。
/**
* Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
* @param nums
* @return
*/
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums.length < 3 || nums ==null) {
return result;
}
Arrays.sort(nums);
int target;
for(int i=0;i<=nums.length-3;i++) {
if(i>0 && nums[i-1]==nums[i]) {
continue;
}
target = -nums[i];
int minIndex = i+1;
int maxIndex = nums.length -1;
while(minIndex<maxIndex) {//当最小index小于最大时
int sum = nums[minIndex]+nums[maxIndex];
if(sum==target) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[minIndex]);
list.add(nums[maxIndex]);
result.add(list);
int prevLow=nums[minIndex];
while(minIndex<maxIndex && nums[minIndex]==prevLow) {//当其值一直相等时,一直往后进行拓展,效率优化
minIndex++;
}
}else if(sum > target) {
maxIndex--;
}else {
minIndex++;
}
}
}
System.out.println(result);
return result;
}