LeetCode(001)-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

翻译:

给定一个整数数组,返回两个数字的索引,使它们加起来等于一个特定的目标。
您可以假设每个输入都只有一个解决方案,并且不能两次使用相同的元素

方法一:使用集合,一次遍历达到目标;创建一个HashMap集合(key为数组的值value为对应数组角标),在遍历数组的过程中,我们判断target-nums[i] 的差值是否是map中元素的key值,如果是那么说明找到两个数相加为target的值,如果没有找到那么就将数组的值和角标压入集合中;
class Solution {
    public int[] twoSum(int[] nums, int target) {
     Map<Integer,Integer> map=new HashMap();
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(target-nums[i])){ //判断key值中是否包含两者差值
                int [] res=new int [2];
                res[1]=i;
                res[0]=map.get(target-nums[i]);//通过key得到value;
                return res;
            }
            map.put(nums[i],i); //将数组元素和角标压入集合中;
        }
        return new int [2];
    }
}
方法二:暴力法

进行双层for循环,将数组中每一个值与其它值相加进行组合;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i=0 ;i<nums.length-1 ; i++){
        //注意角标,i没有必要到最后一个角标,因为需要的是两个数相加的值
            for(int j= i+1 ;j < nums.length ;j++){
                if(target==nums[i]+nums[j])
                    return new int [] {i,j};
            }
        }
        return new int [2];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值