I do not understand the 3ms java solution


  • 0
    J

    3ms solution is:

    class Solution {
        public int[] twoSum(int[] nums, int target) {
    
            int min = Integer.MAX_VALUE;
            int max = Integer.MIN_VALUE;
            for (int num : nums) {
                if (num < min) {
                    min = num;
                }
                if (num > max) {
                    max = num;
                }
            }
            int validMin = Math.max(min, target - max);
            int validMax = Math.min(max, target - min);
    
            int length = validMax - validMin + 1;
            int[] array = new int[length];
            int offset = validMin;
            Arrays.fill(array, -1);
    
            for(int i = 0 ; i != nums.length ; ++i) {
                int num = nums[i];
                if (num >= validMin && num <= validMax) {
                    int firstIndex = array[num - offset];
                    if (firstIndex == -1) {
                        int diff = target - num;
                        array[diff - offset] = i;
                    } else {
                        return new int[]{firstIndex, i};
                    }
                }
            }
    
            throw null;
        }
    }
    

    result is right,but I do not understand
    What principle is it based on?
    Thanks.


Log in to reply
 

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