My Java solution , 3ms, beat 99.87%


  • -1
    S

    public class Solution {
    public int[] twoSum(int[] nums, int target) {
    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
    for(int i = 0, j = nums.length; i < j; i++){
    max = Math.max(max, nums[i]);
    min = Math.min(min, nums[i]);
    }
    if(min < 0){
    for(int i = 0, j = nums.length; i < j; i++){
    nums[i] -= min;
    }
    max -= min;
    target -= 2 * min;
    min -= min;
    }
    for(int i = 0, j = nums.length; i < j; i++){
    nums[i] += max;
    }
    target += 2 * max;
    int[] t = new int[target - min + 1];
    Arrays.fill(t, -1);
    for(int i = 0, j = nums.length; i < j; i++){
    if(t[nums[i]] != -1)
    return new int[]{t[nums[i]], i};
    t[target - nums[i]] = i;
    }
    return null;
    }
    }


Log in to reply
 

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