【leetCode】之Two Sum

20 篇文章 0 订阅
16 篇文章 0 订阅

想尝试着找实习,那么就要开始闭关刷题了。

看了下leetCode的第一个,真的是把大学的底子都忘光了【叹气.jpg】

错误百出,不过也总结下:

题目:

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].

大学接触比较多的是C++相关代码,解题思路:

由于要求的是在同一数组里是否存在两数之和为目标值,所以我用两个变量i,j存放数组下标。让nums[i]+nums[j] 与target比较,相同则返回。

当然我提交出错了几遍,记录如下:

1.

Runtime Error Message: AddressSanitizer: heap-buffer-overflow on address 0x6020000000bc at pc 0x0000004060a6 bp 0x7ffd786a6100 sp 0x7ffd786a60f8

Last executed input: [3,2,4] 6

出错原因:下标引用出错,数组长度我用sizeof(nums)/sizeof(nums[0])计算的,出错,更改==>nums.size()

2.

Wrong Answer:

Input: [0,4,3,0] 0

Output: []

Expected: [0,3]

出错原因:考虑不周全,为了循环少一点,在两层循环里设置了条件:if(nums[i] >= target) continue;  //画蛇添足!!

3.

Wrong Answer:

Input: [-3,4,3,90] 0

Output: []

Expected: [0,2]

出错原因:在上一步里因为没考虑0,而这次是没考虑复数,so~

 

正确C++代码:

​
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        
        //int len = sizeof(nums) / sizeof(nums[0]);

        int len = nums.size();
        vector<int> res; //返回vector类型
        
        for(int i=0;i<len;i++){ //两数相加,外层循环控制第一个数值
            
            //if(nums[i] > target) continue; 
            
            for(int j=i+1;j<len;j++){ //第二个数值
                
               // if(nums[j] > target) continue;

                if(nums[i] + nums[j] == target){ //判断两数相加值是否为所给的目标值
                    //将满足条件的数值插入容器尾部并返回
                    res.push_back(i);  
                    res.push_back(j);
                    return res;
                }  
            }
        }
        return res;
    }
};

​

python3代码:

class Solution:
    def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
        for k in range(len(nums)):
            for l in range(k+1,len(nums)):
                if nums[k] + nums[l] == target:
                    return [k,l]

​

​

java不太熟悉,以后学习了在来更新,不过时空上的消耗都是C++少点,当然python的代码是真的简短~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值