1. 程式人生 > >1.Two Sum

1.Two Sum

leet mark pro close -1 ole 數字 cnblogs view

題目鏈接:https://leetcode.com/problems/two-sum/description/

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

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

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

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

解決辦法一:兩個for循環,依次遍歷,時間復雜度是o(n^2),空間復雜度是o(1)

技術分享
    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)

技術分享
 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

1.Two Sum