Could some one please point out the bug for me?


  • 0
    L
    public class Solution {
        public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            int result = nums[0] + nums[1] + nums[nums.length - 1];
            for (int i = 0; i < nums.length -2; i++){
                if (i > 0 && nums[i] == nums[i-1]){
                    continue;
                    
                }
                int j = i +1; 
                int k  = nums.length - 1;
                
                while (j < k){
                    if (nums[j] + nums[k] + nums[i] == target) {
                        return target;
                    } else if (nums[j] + nums[k] + nums[i] > target) {
                        k--;
                    } else{
                        j++;
                    }
                    if (Math.abs(nums[j] + nums[k] + nums[i] - target) < Math.abs(result - target)) {
                        result = nums[j] + nums[k] + nums[i];
                    }
                }
            
            }
            
            return result;
        }
    }
    

    Above are my code. The logic is pretty much the same as everybody but it just won't result correctly. For example, for input of [-1, 2, 1, -4]
    1

    My code gives 1 when it should have been 2, but I can't figure out why it does that.

    TIA


Log in to reply
 

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