Sharing my concise java solution


  • 9
    M
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i=0; i<numbers.length; i++){
                map.put(numbers[i], i+1);
            }
            for (int i=0; i<numbers.length; i++){
                if (map.get(target - numbers[i]) != null && map.get(target - numbers[i]) > i+1){
                    int[] result = new int[2];
                    result[0] = i+1;
                    result[1] = map.get(target - numbers[i]);
                    return result;
                }
            }
            return null;
        }
    }

Log in to reply
 

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