1.Two Sum

題目連接數組

題目大意:輸入一個數組和一個整數,輸出數組中兩個數字之和是這個整數的這兩個數字的下標,不能使用兩次同一個數字。ide

測試用例:輸入{2, 7, 11, 19}  9  輸出 [0, 1]測試

    輸入{3, 3}  6 輸出[0, 1]spa

    輸入{3, 2, 4}  6  輸出[1, 2]3d

法一:兩個for循環,依次遍歷,時間複雜度是o(n^2),空間複雜度是o(1)。代碼以下:code

    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2];
        boolean mark = false;
        for(int i = 0; i < nums.length; i++) {
            for(int j = i + 1; j < nums.length; j++) {
                if(nums[i] + nums[j] == target) {
                    ans[0] = i;
                    ans[1] = j;
                    mark = true;
                    break;
                }
            }
            if(mark == true) {
                break;
            }
        }
        return ans;
        }    
View Code

法二:先對原數組進行排序,而後兩個標記分別從數組左邊和右邊進行遍歷,若是兩數之和大於target,則右標記--;若是兩數之和小於target,則左標記++;不然找到該兩數。時間複雜度o(nlogn),空間複雜度o(n)。代碼以下:blog

 1     public int[] twoSum(int[] nums, int target) {
 2         int length = nums.length;
 3         int[] tmp = new int[length];
 4         System.arraycopy(nums, 0, tmp, 0, length);
 5         Arrays.sort(nums);
 6         int[] answers = new int[2];
 7         answers[0] = answers[1] = -1;
 8         for(int i = 0, j = length - 1; i < length && j > i; ) {
 9             if(nums[i] + nums[j] < target) {
10                 i++;
11             }
12             else if(nums[i] + nums[j] > target) {
13                 j--;
14             }
15             else {
16                 for(int t = 0; t < length; t++) {
17                     if(tmp[t] == nums[i] && answers[0] == -1) {
18                         answers[0] = t;
19                     }
20                     else if(tmp[t] == nums[j]) {
21                         answers[1] = t;
22                     }
23                 }
24                 break;
25             }
26         }
27         return answers;
28     }
View Code

法三(借鑑):利用hashmap,將原數組存入,再一次遍歷源數組便可獲得結果。時間複雜度o(n),空間複雜度o(n) 。代碼以下:排序

 1     public int[] twoSum(int[] nums, int target) {
 2         //存入hashmap
 3         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 4         int length = nums.length;
 5         for(int i = 0; i < length; i++) {
 6             map.put(nums[i], i);
 7         }
 8         int[] ans = new int[2];
 9         //依次遍歷hashmap進行計算
10         for(int i = 0; i < length; i++) {
11             int num = target - nums[i];
12             if(map.containsKey(num) && map.get(num) != i) {
13                 ans[0] = i;
14                 ans[1] = map.get(num);
15             }
16         }
17         return ans;
18     }
View Code
相關文章
相關標籤/搜索