求数组中三个数字相加等于0 的组合情况

今天又碰到一个问题,
我认为它是很经典的效率优化问题,在我写注释的地方,假如不加上这一段,在输入数组为
[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; 
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值