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> threeSum(int[] nums) {
    List> 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

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(sumMath.abs(sum-target))
                res = sum;
        }
    }
    return res;
}

你可能感兴趣的:(算法)