leetcode1.Two Sum
来源:互联网 发布:mac怎么分盘储存文件 编辑:程序博客网 时间:2024/06/07 00:07
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].//两个指针由两边向中间class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { int m=0,n=0;//m用于记录下标,n用于记录找到了几个数,当n为2时,说明已经找到了 vector<int> sorted(nums);//把nums复制给sorted auto i=sorted.rbegin(); auto j=sorted.rend(); sort(i,j);//对sorted进行由小到大排序 i=sorted.rbegin(); j=sorted.rend(); --j;//i指向sorted的第一个数,即最小数;而j指向sorted的最后一个数,即最大的数 //在sorted数组中找到和为target的两个数 while(i!=j) { if(*i+*j==target) break; else if(*i+*j<target)//当两数的和小于target时,说明较小的数小,移到下一个 ++i; else --j;//否则,大数大,移到前一个 } vector<int> a;//保存下标的数组 for(auto ai:nums)//遍历nums。找到nums之中的这两个数,然后用m记录下标, { if(ai==*i) {a.push_back(m);++n;} else if(ai==*j) {a.push_back(m);++n;} ++m; if(n==2) return a; } return a; } };
阅读全文
0 0
- [LeetCode1] Two Sum
- LeetCode1 Two Sum
- Leetcode1:Two Sum
- leetcode1 two sum
- LeetCode1 Two Sum
- LeetCode1:Two Sum
- leetcode1 Two Sum题解
- leetcode1 Two Sum
- LeetCode1 Two Sum
- LeetCode1:Two Sum
- leetCode1: Two Sum
- leetcode1--Two Sum
- leetcode1 Two Sum
- LeetCode1. Two Sum
- Leetcode1:Two Sum
- leetcode1.Two Sum
- leetcode1 Two Sum
- LeetCode1-Two Sum
- cvc-complex-type.2.4.a: Invalid content was found starting with element
- 人工智能在中国的崛起:中国将再次领导世界?
- Intellij 中的git操作
- [C# 网络编程系列] 专题二:HTTP协议详解
- WebRTC视频帧渲染前处理——视频帧裁剪
- leetcode1.Two Sum
- 算法第2篇——插入排序
- PullToRefreshListView原理解析(二)
- 字符串的连接,以及字符串大小写的转换
- getWidth和getMeasureWidth区别
- java Collections.sort()排序。List排序
- 用PL/SQL Developer创建Oracle触发器以及触发器的一点点知识与出现的问题
- Handlebars一些
- 普通按钮和图片按钮