LeetCode:1_TwoSum--C++实现
来源:互联网 发布:笔记本电脑必备软件 编辑:程序博客网 时间:2024/06/10 15:29
#include <iostream>#include <vector>using namespace std;/* LeetCode 1.TwoSum 题目要求: 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. 返回索引位置即可; 题目假设给出的集合仅仅只有一个满足的a+b==target:assume that each input would have exactly one solution ==================== 想到另一种办法:用target-a得到b,在集合中搜索存不存在b即可;可以使用HashMap等快速搜索容器 ====================*/vector<pair<int,int>> two_sum(vector<int>& nums,int target){ //auto iter = nums.cbegin(); vector<pair<int,int>> ret; //容纳返回值 int sum = 0; int first_index = 0; //a+b==target中a的索引位置 int index = -1; //循环次数:对应nums中的索引 bool hadFirst = false; //是否已取得第一个数 for(auto i : nums){ ++index; if(i > target) continue; if(sum + i > target) continue; if(hadFirst) { if(sum + i == target) { ret.push_back(pair<int,int>{first_index,index}); hadFirst = false; sum = 0; } else //sum + i < target continue; } else { first_index = index; sum = i; hadFirst = true; } } return ret;}int main(){ vector<int> nums = {20,2,7,5,8,11,9,3}; int target = 10; auto ret = two_sum(nums,target); for(auto i : ret) { cout<<i.first<<":"<<i.second<<"<--->" <<nums[i.first]<<"+"<<nums[i.second]<<"=="<<target<<endl; } return 0;}
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.
阅读全文
0 0
- LeetCode:1_TwoSum--C++实现
- 1_TwoSum
- 1_twoSum
- [LeetCode]1 Two Sum(C++,Python实现)
- LeetCode-1-Two Sum(C语言实现)
- C实现 LeetCode-> TwoSum
- C实现 LeetCode->LongestCommonPrefix
- C实现 LeetCode->RemoveNthNodeFromEndofList
- C实现 LeetCode->Palindrome Number
- C实现 LeetCode->Reverse Integer
- C实现 LeetCode->3Sum
- C实现 LeetCode->3SumClosest
- C实现 LeetCode->4Sum
- C实现 LeetCode->Valid Parentheses
- LeetCode 之 Number of 1 Bits — C 实现
- [C++]LeetCode #1 twoSum
- [leetcode](Gray Code 格雷码 C语言实现)
- [leetcode](Add Binary C语言实现)
- Still unable to dial persistent://xxx:80 after 3 attempts
- 毫秒级别的时间差
- linux系统调用分析
- python钩子脚本
- java如何得到GET和POST请求URL和参数列表(转载)
- LeetCode:1_TwoSum--C++实现
- 【转载】京东资深架构师代码评审歪诗
- Mysql sql语句一些需要注意的坑
- [YZOJ]P1397-奔跑的骑士-矩阵建模
- pc端点击图片放大效果
- ConfigReader(十二)—— ReadGuideClickButtonTaskConfig
- 解决utf-8编码下 echo 弹出javascript alert中文乱码解决方法
- cudamat安装
- 作业1平均数2