美文网首页
1、两数之和-LeetCode

1、两数之和-LeetCode

作者: 0Xday | 来源:发表于2018-07-21 12:39 被阅读0次

题目:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。


给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]


解决思路:

使用ArrayList保存中间值,A=target-B,遍历数组,在list中未找到A时,
一直往list中添加B,直到list中含有A时,输出A、B的索引位置


public int[] twoSum(int[] nums, int target) {
   
    ArrayList<Integer> list=new ArrayList<>();//建立list,存储中间值
    
    int [] re=new int[2];//结果值
    for(int i=0;i<nums.length;i++){
        //查找list中是否含有该temp,有则输出[temp在list的位置,i],没有则list.add(nums[i])
        int temp=target-nums[i];    
        if(list.contains(temp)){
            re[0]=list.indexOf(temp);
            re[1]=i;
        }else{
             //只有list中没有temp值就add,这样可以使对应的temp值的索引与其在数组中的一致
            list.add(nums[i]);     
        }
    }
    return re;
    
}

相关文章

网友评论

      本文标题:1、两数之和-LeetCode

      本文链接:https://www.haomeiwen.com/subject/jrlhmftx.html