1. 两数之和

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

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

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

代码

  public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> datas = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(datas.containsKey(nums[i])) {
                Integer k = datas.get(nums[i]);
                return new int[]{k,i};
            }else {
                int k = target - nums[i];
                datas.put(k,i);
            }
        }
        throw new RuntimeException("未找到");
    }

分析

主要是利用map集合来存储值,存储的是下一下要找的值和当前的索引,然后找到的时候就可以知道这两个索引

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容