Accepted code in JAVA


  • 0
    S

    public class Solution {

    public int[] twoSum(int[] numbers, int target) {
        int[] res=new int[2];
        if(numbers==null||numbers.length<2) return res;
        HashMap<Integer,ArrayList<Integer>> hm=new HashMap<Integer,ArrayList<Integer>>();
        
        for(int i=0;i<numbers.length;i++)
        {
            
            if(hm.containsKey(numbers[i]))
            {
                hm.get(numbers[i]).add(i);
            }
            else
            {
            	ArrayList<Integer> indexArr=new ArrayList<Integer>();
            	indexArr.add(i);
            	hm.put(numbers[i],indexArr);
            }
            
            
        }
        for(int i=0;i<numbers.length;i++)
        {
            if(hm.containsKey(target-numbers[i]))
            {
                boolean isDouble=target==2*numbers[i];
            	if(isDouble&&hm.get(numbers[i]).size()!=1)
                {
                    
                   res[0]=hm.get(numbers[i]).get(0)+1;
                   res[1]=hm.get(numbers[i]).get(1)+1;
                   break;
                    
                }
                else if((!isDouble)&&hm.get(numbers[i]).size()==1)
                {
                	res[0]=hm.get(numbers[i]).get(0)+1;
                	res[1]=hm.get(target-numbers[i]).get(0)+1;
                	break;
                }
                
            }
        }
        return res;
       
    }
    

    }


Log in to reply
 

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