Accepted Java O(n) solution


  • 0
    L

    import java.util.Arrays;
    class Solution {
    public int[] twoSum(int[] nums, int target) {
    int[] originalArray = Arrays.copyOf(nums,nums.length);
    Arrays.sort(nums);
    int[] results = new int[2];
    int[] finalresults = new int[2];
    finalresults[0]=-1;
    finalresults[1]=-1;
    int pointer1=0;
    int pointer2=nums.length-1;
    while(pointer1<pointer2)
    {
    int sum=nums[pointer1]+nums[pointer2];
    if (sum==target)
    {
    results[0]=nums[pointer1];
    results[1]=nums[pointer2];
    break;
    }
    else if (sum>target)
    pointer2--;
    else if (sum<target)
    pointer1++;
    }

        for (int i=0; i<nums.length; i++)
        {
            if (originalArray[i]==results[0] && finalresults[0]==-1)
                finalresults[0]=i;
            else if (originalArray[i]==results[1])
                finalresults[1]=i;
        }
        Arrays.sort(results);
        return finalresults;
    }
    

    }


Log in to reply
 

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