Simple Java solution with Sorting


  • 0
    K
    public int[] twoSum(int[] nums, int target) {
            int[] sortArray = nums.clone();
            Arrays.sort(sortArray);
            int[] result=new int[2];
            for(int i=0; i< sortArray.length;i++){
                for(int j=i; j< sortArray.length; j++){
                    if(sortArray[i]+sortArray[j]==target){
                        for(int k=0; k<sortArray.length; k++){
                            if(nums[k]==sortArray[i] || nums[k]==sortArray[j]){
                                result[0]=k;
                                break;
                            }
                        }
                        for(int k=result[0]+1; k<sortArray.length; k++){
                            if(nums[k]==sortArray[i] || nums[k]==sortArray[j]){
                                result[1]=k;
                            }
                        }
                        return result;
                    }
                    
                }
                
            }
            
            return result;
            
        }
    

Log in to reply
 

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