LeetCode Algorithms #1 Two Sum
来源:互联网 发布:昆明行知中学招聘 编辑:程序博客网 时间:2024/06/05 16:48
LeetCode Algorithms #1 Two Sum
题目内容
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].
解题
最简单的解法
最简单的,不用说,自然是双层循环枚举所有组合,时间复杂度为
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { int length = nums.size(), i, j; bool flag = true; //为的是得到结果之后快速跳出循环 for(i = 0; i < length && flag; i++) { for(j = i+1; j < length && flag; j++) { if(nums[i]+nums[j] == target) flag = false; } } vector<int> result; result.push_back(i-1); result.push_back(j-1); return result; }};
但是这样自然是很慢的,我的运行时间是133ms,只超过了30.73%的人。
更快的方法
不知道为什么,看到这道题的时候第一个想法就是排序之后夹逼,但是由于题目中给的是vector<int>
,如果排序的话要在排序的过程中将其索引值也交换,才能正确的indice,其中的假想是否成立也没有经过仔细考虑。不过为了刷时间,还是想了一下这个想法。
首先有一点是由于题目明确给出答案存在并且唯一的,不会因为std::sort()
的不稳定性返回错误的答案(比如要求返回第一对满足的结果,std::sort()
将几个相同值的索引打乱后没法确定第一个)。
没有经过详细的证明,只是简单的想了一下情况。假设这个方法不正确的,那不正确的过程应该发生在某一个标记值跨过
#include <algorithm>#include <utility>struct node { int value; int index; node(int a, int b):value(a), index(b){}};bool compare(const node* a, const node* b) { return a->value < b->value;}class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { int rear = nums.size()-1, head = 0; vector<node*> n; for(int i = 0; i <= rear; ++i) n.push_back(new node(nums[i], i)); sort(n.begin(), n.end(), compare); int sum; while(rear > head) { sum = n[head]->value + n[rear]->value; if(sum == target) break; else if(sum > target) --rear; else ++head; } int a = n[head]->index, b = n[rear]->index; if(a > b) swap(a, b); vector<int> result; result.push_back(a); result.push_back(b); return result; }};
最后是运行时间6ms,超过82.12%。
- LeetCode Algorithms #1 Two Sum
- leetcode algorithms: two sum
- Leetcode-Algorithms Two Sum
- [LeetCode-Algorithms-1] "Two Sum" (2017.9.8)
- LeetCode Algorithms 1. Two Sum
- leetcode Algorithms 1. Two Sum
- 算法设计Week1 LeetCode Algorithms Problem #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
- leetcode-1 Two Sum
- python爬虫备忘(2)
- SQL Tuning 基础概述03
- QML与C++交换数据
- FastDFS文件集群服务器搭建
- python 在Windows 下切换工作目录
- LeetCode Algorithms #1 Two Sum
- 正则表达式:检测密码由6-21字母和数字组成
- Android OpenGL ES 投影矩阵的设置
- [笔记分享] [Git] progit学习笔记之分支
- 决策树原理
- html高德地图ip定位之后拖动自定义定位地址
- JavaWeb学习篇之----自定义标签&&JSTL标签库详解
- DHCP报文
- JAVA面试题---用java程序遍历二叉树(递归与非递归)