Two-sum, i don't know where is wrong


  • 0
    X
    public int[] twoSum(int[] numbers, int target) {
      
        if (numbers == null || numbers.length <= 1)
            return null;
        //use a hashset to solve this questin might be good
        HashSet<Integer> set = new HashSet<Integer>();
        int[] res = new int[2];
        for (int i = 0; i < numbers.length; i++){
            set.add(target - numbers[i] ); //add remain into set
        }
        int index1 = 0;
        int index2 = 0;
        for (int i = 0; i < numbers.length; i++){
            if (set.contains(numbers[i])){
                index1 = i;
                continue;
            }
        }
        
        for (int i = 0; i < numbers.length; i++){
            if (numbers[i] == target - numbers[index1]){
                if (index1 != i)
                    index2 = i;
            }
        }
        res[0] = index2+1;
        res[1] = index1+1;
        return res;
    }
    

    }


Log in to reply
 

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