具体题目请访问题目链接:https://leetcode-cn.com/problems/two-sum/
思路:
1 暴力,两层循环直接干上去,这样干上去简单好做,但是可能就今天面试就到这里吧,等通知。
2 利用hash表存储,取代调一层循环 key存储数组具体的值,value存储数组的下标,判断hash表里是否包含这个数,包含则说明找到了。没有包含则把自己加到hash表里去,继续下一个寻找。
class Solution { public int[] twoSum(int[] nums, int target) { // 在一个集合里去找,看有不有 key存值,value 存 第几个 Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for (int i = 0; i < nums.length; i++){ // 如果 map 有,则找到了这个值 if (map.containsKey(target - nums[i])){ return new int[]{map.get(target - nums[i]),i}; } map.put(nums[i],i); } return new int[0]; } }
原文:https://www.cnblogs.com/junbaba/p/14124022.html