C# Solution


  • 0
    H

    Similar to Problem '3Sum'

    public class Solution {
        public int ThreeSumClosest(int[] nums, int target) {
            int result = 0, min = Int32.MaxValue, dis, origin;
            if(nums == null || nums.Length < 3) return result;
            int len = nums.Length, l, r, ni;
            Array.Sort(nums);
            for(int i = 0; i < len - 2; i++)
            {
                ni = nums[i];
                if(i > 0 && ni == nums[i - 1]) continue;
                l = i + 1;
                r = len - 1;
                while(l < r)
                {
                    origin = nums[l] + nums[r] + ni;
                    dis = Math.Abs(origin - target);
                    if(dis == 0)   return target;
                    if(dis < min)
                    {
                        result = origin;
                        min = dis;
                    }
                    if(origin < target)
                    {
                        while(++l < r && nums[l] == nums[l - 1]);
                    }
                    else
                    {
                        while(--r > l && nums[r] == nums[r + 1]);
                    }
                }
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.