TwoSum

作者: Allllliy | 来源:发表于2019-01-04 18:52 被阅读0次

今天开始刷leetcode,第一篇博客就从第一道题开始吧~
描述:给一个整数数组,返回两个数的索引,使他们相加等于target,有且只有一个解。
举例:
nums = [2, 7, 11, 15], target = 9,
因为 :nums[0] + nums[1] = 2 + 7 = 9;
return [0, 1]

最容易想的就是暴力求解~
暴力法(时间复杂度O(n2)):

class Solution {
    int a[] = new int[2];
    public int[] twoSum(int[] nums, int target) {
        for(int i=0; i<nums.length-1; i++){
            for(int j=i+1; j<nums.length; j++){
                if((nums[i] + nums[j]) == target){
                    a[0] = i;
                    a[1] = j;
                    break;
                }
            }
        }
        return a;
    } 
}

显然时间复杂度过高了。

参考了一下时间复杂度O(n)的方法,那就是利用HashMap。遍历数组,建立Map映射,在遍历时寻找满足条件的值(即target - a = b):

public int[] twoSum(int[] numbers, int target) {
    int[] result = new int[2];
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < numbers.length; i++) {
        //如果此映射包含指定键的映射关系,则返回 true
        if (map.containsKey(target - numbers[i])) {
            result[1] = i;
            //返回指定键所映射的值;如果此映射不包含该键的映射关系,则返回 null
            result[0] = map.get(target - numbers[i]);
            return result;
        }
        //将指定的值与此映射中的指定键关联
        map.put(numbers[i], i);
    }
    return result;
}

当然,还可以用python~就是慢了点:
因为python字典也是一个hash table,所以索引的时间复杂度是O(1),因此这么写的复杂度也是O(n)

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        for i in range(len(nums)):
            if nums[i] in dict:
                return [dict[nums[i]], i]
            else:
                dict[target - nums[i]] = i

相关文章

  • TwoSum

    题目大意: 找到数组中两个元素相加等于指定数的所有组合 情况一:给定数组中不含重复元素,且均为正整数 思路: 使用...

  • twoSum

    Problem Given an array of integers, return indices of the...

  • TwoSum

    刷题当然要从TwoSum开始了~~python刷题果然容易~~~class Solution(object):de...

  • TwoSum

    介绍:Two Sum给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。函数 twoSum 返回这两个相...

  • TwoSum

  • TwoSum

    Problem### Given an array of integers, find two numbers s...

  • TwoSum

    简单方法,两边循环,一个推着另一个,复杂度n2 使用map,检查过的存起来map,每拿到一个新的,就去map里查,...

  • TwoSum

    题目描述: Given an array of integers, return indices of the t...

  • twoSum

    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。 你需要实现的函数twoSum需要返回这两个...

  • TwoSum

    暴力暴力算法时间复杂度O(n²),空间复杂度O(1) 两次遍历 HashMap时间复杂度:O(n),我们把包含有 ...

网友评论

      本文标题:TwoSum

      本文链接:https://www.haomeiwen.com/subject/rjvkrqtx.html