leetcode經典題目及解法記錄

Question15 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]
]
解法如下:

public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> res = new ArrayList();
    Arrays.sort(nums);
    for(int i = 0; i < nums.length; i++){
        if(i==0||(i>0&&nums[i]!=nums[i-1])){
            int lo=i+1, hi=nums.length-1, sum=0-nums[i];
            while(lo<hi){
                if(nums[lo]+nums[hi]==sum){
                    res.add(Arrays.asList(nums[i], nums[lo], nums[hi]));
                    while(lo<hi&&nums[lo]==nums[lo+1]) lo++;
                    while(lo<hi&&nums[hi]==nums[hi-1]) hi--;
                    lo++;
                    hi--;
                }else if(nums[lo]+nums[hi]<sum)
                    lo++;
                else
                    hi--;
            }
        }
    }
    return res;
}

Question16 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 int threeSumClosest(int[] nums, int target) {
    int res = nums[0]+nums[1]+nums[nums.length-1];
    Arrays.sort(nums);
    for(int i = 0; i < nums.length-2; i++){
        int lo = i+1, hi = nums.length-1;
        while(lo < hi){
            int sum = nums[i]+nums[lo]+nums[hi];
            if(sum==target)
                return sum;
            if(sum<target)
                lo++;
            else
                hi--;
            if(Math.abs(res-target)>Math.abs(sum-target))
                res = sum;
        }
    }
    return res;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章