知足两数之和的下标 Two Sum

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.ci

Example:element

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解决方法:get

①暴力破解,第一层循环给定一个数nums[i],第二层循环查找符合nums[j] == target - nums[i]的值,从第i+1个数开始查找。思路最简单,用时48msinput

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0;i < nums.length ;i ++ ) {
            for (int j = i + 1;j < nums.length ;j ++ ) {
                if (nums[j] == target - nums[i]) {//使用条件nums[j]+nums[i]==target也能够
                    return new int[]{i,j};//注意返回数组的方式
                }
            }
        }
        return null;//由于题目给定的情景不会出现这种状况,因此随意返回
    }
hash

时间复杂度:O(n^2)由于要双重循环遍历值,空间复杂度:O(1)io

②双向hash表,比较快速的方法是使用HashMap来存放数值及其下标,而后使用map的方法来查找另外一个值。用时11msclass

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for (int i =0;i < nums.length ;i ++ ) {
            map.put(nums[i],i);
        }
        for (int i =0;i < nums.length ;i ++ ) {
            int sub = target - nums[i];
            if(map.containsKey(sub) && map.get(sub) != i){//注意map方法及其返回值。
                return new int[]{i,map.get(sub)};
            }
        }
        return null;
    }
循环

时间复杂度:O(n),由于使用了hash方法查找第二个值。空间复杂度:O(n),新建了hash map。遍历

相关文章
相关标签/搜索