LeetCode 1.Two Sum

来源:互联网 发布:ubuntu cat命令 编辑:程序博客网 时间:2024/06/03 04:12

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 thesame element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].


方法一:
【双重for循环暴力破解】
    时间复杂度O(n^2);

方法二:
【空间换时间】
    时间复杂度O(n);
    public int[] twoSum(int[] nums, int target) {        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();        int[] res = new int[2];        for(int i = 0; i < nums.length; i++){            m.put(nums[i],i);        }        for (int i = 0; i < nums.length; i++) {            if (m.containsKey(target - nums[i]) && m.get(target - nums[i]) != i) {                res[0] = i;                res[1] = m.get(target - nums[i]);                break;            }        }        return res;    }
方法三:
对方法二的优化
    public int[] twoSum(int[] nums, int target) {        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();        int[] res = new int[2];        for (int i = 0; i < nums.length; i++) {            if (m.containsKey(target - nums[i])) {                res[0] = m.get(target - nums[i]);                res[1] = i;                break;            }            m.put(nums[i],i);        }        return res;    }