LeetCode系列之Two sum

来源:互联网 发布:金字塔软件官网 编辑:程序博客网 时间:2024/06/03 17:21

问题描述

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.

我来翻译一下:也就是给一个数组和一个两数的和,让你从这个数组中找到两个数加起来等于这个和,给出在数组中的位置

注意下一句才是重点:假设一组输入中有且只有一组满足这个条件,并且给的数组没有重复的元素

思考:

  1. 当然是按个遍历一遍,也就是类似于倒三角样式的遍历,复杂度n*n
for(int i = 0;i < nums.length;i++){            for (int j = i + 1; j < nums.length; j++) {                if (nums[i] + nums[j] == target) {                    result[0] = i;                    result[1] = j;                    break;                }            }        }
2.思考题目中最后一句话能发现一些玄机,只有一组满足条件,并且没有重复元素,这句话就是告诉我们只用遍历一次就能得出结论,在看了别人的优解之后还是挺佩服的
 Map<Integer, Integer> map = new HashMap<Integer, Integer>();    for (int i = 0; i < numbers.length; i++) {        if (map.containsKey(target - numbers[i])) {            result[1] = i + 1;            result[0] = map.get(target - numbers[i]);            return result;        }        map.put(numbers[i], i + 1);    }
  • 利用map存储key的hash特性使得找key的复杂度是常数
  • 利用没有重复元素使得key值唯一
  • 利用只有一组解大胆return,不继续剩下的元素

大神解法链接:leetcode:two sum,id:jiaming2

原创粉丝点击