Blazing fast Java solution


  • 0
    A

    Beat >98% of Java solutions:

    public class Solution {
        public int[] helper(int[] nums, int a, int b){
            int soln[] = new int[2];
            for(int i = 0; i < nums.length; i++){
                if(nums[i] == a){
                    soln[0] = i;
                    break;
                }
            }
             for(int i = 0; i < nums.length; i++){
                if((nums[i] == b) && (soln[0] != i)){
                    soln[1] = i;
                    break;
                }
            }
                Arrays.sort(soln);
                return soln;
        }
        public int[] twoSum(int[] nums, int target) {
            int [] solution = new int[2];
            int index;
            int[] new_arr = new int[nums.length];
            for(int j = 0; j < new_arr.length; j++){
                new_arr[j] = nums[j];
            }
            Arrays.sort(nums);
            for(int i =0; i < nums.length; i++){
              if(target - nums[i] < nums[i]){
                  index = Arrays.binarySearch(nums, 0, i, target - nums[i]);
                if(index > 0){
                    solution = helper(new_arr, nums[i], nums[index]);
                    return solution;
                }
              } else{
                  index = Arrays.binarySearch(nums, i+1, nums.length, target - nums[i]);
                if(index > 0){
                    solution = helper(new_arr, nums[i], nums[index]);
                    return solution;
                }
              }
            }
            return solution;
      }
    }
    

    If anything is unclear, let me know. I just did binary searches and duplicated the original array so that I could sort the indices at the end.


Log in to reply
 

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