C# solution


  • 0
    K
    public class Solution {
        public int ThreeSumClosest(int[] nums, int target) {
            int len = nums.Length;
            int total = 0;
            int diff = 0;
            int result = 0;
            int olddiff = Int32.MaxValue;
            
            Array.Sort(nums);
    
            for (int i=0;i<len-2;i++) {
                int j = i+1;
                int k = len-1;
                while (j < k) {
                    total = nums[i]+nums[j]+nums[k];
                    
                    if ( total == target) return total;
                    else if (total < target) j++;
                    else if (total > target) k--;
                    
                    diff = Math.Abs(target - total);
                    if (diff < olddiff) {
                        result = total;
                        olddiff = diff;
                    }                    
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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