Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
 簡單來說,就是給一個數組及一個數值,求陣列中兩元素相加為該數值對應的兩個索引。且要求index1小於index2,而且答案結果穩定。
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] numsUnOrder = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {//原始無序陣列,不能直接使用int[] numsUnOrder = nums;這樣是引用傳遞,指向的還是nums[]
            numsUnOrder[i] = nums[i];
        }
        int[] result = new int[2];
        Arrays.sort(nums);//對陣列做了一次排序,預設升序排列
        int begin = 0;
        int end = nums.length - 1;
        int temp;

        while (begin < end) {
            if (nums[begin] + nums[end] == target) {
                result[0] = nums[begin];//先存放數值
                result[1] = nums[end];
                break;
            } else if (nums[begin] + nums[end] < target) {
                begin++;
            } else if (nums[begin] + nums[end] > target) {
                end--;
            }
        }//while

        for (int i = 0; i < numsUnOrder.length; i++) {//從前往後比較,根據數值在原始無序陣列中查詢下標,並把下標存到result[]中
            if (result[0] == numsUnOrder[i]) {
                result[0] = i;
                break;
            }
        }

        //可能會出現兩個相同的元素,所以需要一個從前往後查詢下標,一個從後往前查詢下標
        for (int i = numsUnOrder.length - 1; i >= 0; i--) {//從後往前比較,根據數值在原始無序陣列中查詢下標,並把下標存到result[]中
            if (result[1] == numsUnOrder[i]) {
                result[1] = i;
                break;
            }
        }

        if (result[0] > result[1]) {//保證result[0]比result[1]小
            temp = result[0];
            result[0] = result[1];
            result[1] = temp;
        }
        return result;
    }//twoSum
}

19 / 19 test cases passed.
Status: Accepted
Runtime: 7 ms
Your runtime beats 92.64 % of java submissions

-------------------------------------------------------

    //AC  方法2
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                if(nums[i] + nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                    return  result;
                }
            }
        }
        return  result;
    }

19 / 19 test cases passed.
Status: Accepted
Runtime: 38 ms
Your runtime beats 29.73 % of java submissions.

時間複雜度是O(n^2),