leetcode刷题之路1 Two Sum

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

自己的思路:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result =new int[2];
        for(int i=0;i

用HashMap的思路:
将数组的值当作key,序号当作value,循环数组,将数组的值和序号放入HashMap中,循环数组中的值,如果数组的HashMap有target-nums[i]这种键值,则记录他的value返回

boolean containsKey(Object key) :如果此映射包含对于指定键的映射关系,则返回 true
V get(Object key) 返回指定键所映射的值;
V put(K key, V value) 在此映射中关联指定值与指定键。

class Solution {
    public int[] twoSum(int[] nums, int target) {
     //判断边界条件
        if(nums == null || nums.length <2){
            return new int[]{-1,-1};
        }
        int [] res = new int[]{-1,-1};
        HashMap map = new HashMap<>();
        for(int i=0;i

你可能感兴趣的:(leetcode(Java))