1.Two Sum

题目链接

题目大意:输入一个数组和一个整数,输出数组中两个数字之和是这个整数的这两个数字的下标,不能使用两次同一个数字。

测试用例:输入{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

法三(借鉴):利用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

 

posted on 2017-08-19 15:12  二十年后20  阅读(191)  评论(0编辑  收藏  举报

导航