java simple solution using hashset


  • 0
    P

    public class Solution {
    public int[] twoSum(int[] numbers, int target) {
    int[] num = new int[2];
    int i = 0;
    HashSet<Integer> set = new HashSet<Integer>();
    while(i<numbers.length)
    {
    if(set.contains(target-numbers[i]))
    {
    for(int j = 0;j<i;j++)
    {
    if(numbers[j] == target-numbers[i])
    {
    num[0] = j+1;
    num[1] = i+1;
    return num;
    }
    }
    }
    else
    {
    set.add(numbers[i]);
    }
    i++;
    }
    return num;
    }
    }


Log in to reply
 

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