【LeetCode】3Sum,3Sum Closest 题解报告

【题目1】3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

【解析】
根据题目的意思,需要在一个数组中找到所有的三元组,使这3个数的和为0.跟Two Sum这道题很像。只不过这道题是找出所有可行的结果,并且结果集中不能存在重复。
这道题依然有两种思路,最直接的想法是进行3重循环,遍历所有的可能,这样的时间效率是O(n^3).显然,时间效率过高。
思路2:先对数组进行排序(递增),效率是O(nlogn),然后先确定第一个值,再在有序的序列中查找两个满足要求的数。由于是有序的,所以查找效率是O(n),因此,总体的时间效率是O(n^2).

public static List<List<Integer>> threeSum(int[] nums) {
    Arrays.sort(nums);
    Set<List<Integer>> res = new HashSet<List<Integer>>();
    for(int i=0;i<nums.length;i++){
        int target = 0 - nums[i];
        int j = i+1, k=nums.length-1;
        while(j<k){
            if(nums[k] + nums[j] == target){
                List<Integer> tmp = new ArrayList<Integer>();
                tmp.add(nums[i]);
                tmp.add(nums[j]);
                tmp.add(nums[k]);
                res.add(tmp);
                j++;
                k--;
            }
            else if(nums[k] + nums[j] < target)
                j++;
            else
                k--;
        }
    }        
       return new ArrayList<List<Integer>>(res);
}

【题目2】3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

【解析】
这道题跟上面的类似,解题思路是一样的。先对数组进行排序,然后确定第一个数,再在有序的数组中遍历找到最接近目标值的数。

public static int threeSumClosest(int[] nums, int target) {
      if(nums == null || nums.length < 3)
          return 0;
       Arrays.sort(nums);
       int res = 0;
       int diff = Integer.MAX_VALUE;
       int len = nums.length;
       for(int i=0;i<len-2;i++){
            int j = i+1, k=len-1;
            while(j<k){
                int sum = nums[i] + nums[j] + nums[k];
                if(Math.abs(sum - target) < diff){
                    diff = Math.abs(sum - target);
                    res = sum;
                }
                if(sum < target){
                    j++;
                }else if(sum > target){
                    k--;
                }else{
                    return sum;
                }
            }           
          }
       return res;
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值