LeetCode---TwoSum

LeetCode Two Sum

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.

Example:

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

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

因为我用的主要开发语言是Java,所以解法都是基于Java的。

解法1:

思路:
遍历数组,每个数字都相加一次,如果等于target,则直接返回下标。如果遍历结束还没有结果,则没有结果,返回[-1,-1]。
Runtime 19ms

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

解法二:(网上学习来的)

思路
遍历一次数组,遍历过的数组就直接存进map,key为数组的值,value为数组的下标,利用map的
containsKey来进行解法一的嵌套for循环遍历,遍历前先进行判断(第一次除外)要找的key是
否存在,如果存在,就将当前值的下标和map中的value返回,不存在就将值和下标存进map。
containsKey方法:判断该Key在map中是否存在,如果存在返回true,不存在返回false.
Runtime 2ms

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result=new int[2];
        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
            if(i==0){
                map.put(nums[i], i);
            }else {
                if(map.containsKey(target-nums[i])) {
                    result[1]=i;
                    result[0]=map.get(target-nums[i]);
                    return result;
                }else {
                    map.put(nums[i], i);
                }
            }
        }
        return new int[] {-1,-1};
    }
}

猜你喜欢

转载自www.cnblogs.com/hlwd/p/10898523.html