LeetCode 1 two sum
来源:互联网 发布:rfid防碰撞算法 编辑:程序博客网 时间:2024/05/22 15: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.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解法一:先排序再找下标,时间复杂度为O(nlogn)
fina1和fina2函数,都是在找下标,一个是从头开始找,一个是从尾部开始找,因为在遍历的时候,一个指针从头开始,一个指针从尾开始。必须这样,因为数组中可能会有相等的元素出现。
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res,temp; copy(nums.begin(),nums.end(),back_inserter(temp)); sort(temp.begin(),temp.end()); vector<int>::iterator ite1 = temp.begin(); vector<int>::iterator ite2 = temp.end()-1; while (ite1 != ite2) { if ( *ite1 + *ite2 == target) { res.push_back(fina1(nums,*ite1)); res.push_back(fina2(nums,*ite2)); break; } else { if (*ite1 + *ite2 < target) ite1++; else ite2--; } } return res; } int fina1(vector<int> num,int tar) { vector<int>::size_type sz = num.size(); for (int i=0;i<sz;i++) { if (num[i]== tar) return i; } return 0; } int fina2(vector<int> num,int tar) { vector<int>::size_type sz = num.size(); for (int i=sz-1;i>=0;i--) { if (num[i]== tar) return i; } return 0; }};
第一道题,看网上还有用map解决的,下来再好好了解一下map,再来补充第二种解法。
0 0
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- 数据结构::关于广义表的那些事~~
- 荒岛求生第九关
- Redis未授权访问缺陷让服务器沦为肉鸡
- oracle中substr和instr
- github 删除github上的项目
- LeetCode 1 two sum
- Matlab教程 学习之基础知识
- Json 转换
- 【android学习】检测android主屏,并把app从后台切换置前台
- (转)英特尔研发AI专用处理器 性能比GPU提升100倍
- session超时或未登录时回到登录界面,如有frame跳出frame
- JQuery内存泄露解决办法
- Android 在代码中设置控件在RelativeLayout的位置
- RxJava+Retrofit+OkHttp深入浅出-终极封装七(异常处理)