O(n) with hash map. java


  • 0
    U
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int[] ans = new int[2];
            Map<Integer, Integer> map = new HashMap<>();
            int g=0;
            for(Integer i : numbers){
                map.put(i,g);
                g++;
            }
            g=0;
            for(Integer i: numbers){
                if(map.containsKey(target-i) && g!=map.get(target -i)){
                    if(i<=target-i){
                        ans[0]=g+1;
                        ans[1]=map.get(target -i)+1;
                    }else{
                        ans[0]=map.get(target -i)+1;
                        ans[1]=g+1;
                    }
                }
                g++;
            }
            return ans;
            
        }
    }
    

Log in to reply
 

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