LeetCode-E-Two Sum
来源:互联网 发布:哪个软件有天九牌游戏 编辑:程序博客网 时间:2024/06/03 20:30
题意
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].
解法
排序 + 双指针
实现
bool mycompare(pair<int,int> a, pair<int,int> b){ return a.first < b.first;}class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; if(nums.size() == 0) return result; vector<pair<int,int>> ivector; for(int i = 0; i < nums.size(); ++i){ ivector.push_back(make_pair(nums[i],i)); } std::sort(ivector.begin(),ivector.end(),mycompare); int start = 0; int end = ivector.size() - 1; while(start < end){ int sum = ivector[start].first + ivector[end].first; if(sum == target){ result.push_back(ivector[start].second); result.push_back(ivector[end].second); return result; }else if(sum < target){ ++start; }else --end; } return result; }};
0 0
- leetcode(E)two sum
- leetcode(E) two sum
- LeetCode-E-Two Sum
- LeetCode-E-Two Sum II
- 1. Two Sum【E】【59+25】【leetcode】
- 【leetcode】371. Sum of Two Integers【E】
- 【Leetcode】Two Sum (Sum)
- leetcode(E)two sumII
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- nfs启动出现网络断开Try to bring eth0 interface up......
- Problem Preparation T
- 看Spring工具类一文,附自己的使用心得(改)
- 14届省赛总结
- 吐槽之Android Studio坑逼的提示功能
- LeetCode-E-Two Sum
- Mysql学习笔记五——having筛选
- 1
- 网易初面(技术面)
- 趁着我还清醒的时候来一发感想
- 2
- saltstack 数据系统——Grains和pillar
- java与javascript语法区别
- citymaker学习资源