leetcode-167-Input array is sorted
来源:互联网 发布:ubuntu grub引导修复 编辑:程序博客网 时间:2024/05/21 06:21
问题
题目:[leetcode-167]
思路
朴素的思路就是两层循环。但是TLE.
代码(TLE)
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int sz = numbers.size(); std::vector<int> ret; for( int i = 0; i < sz - 1; ++i ){ for( int j = i + 1; j < sz; ++j ){ if( numbers[i] + numbers[j] == target ) { ret.push_back(i+1); ret.push_back(j+1); return ret; } } } return ret; }};
思路1
看见有序序列,敏感一点就能想到二分查找。这么做复杂度就是O(nlogn).
代码1
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int sz = numbers.size(); vector<int> ret; if(!sz) return ret; for( int i = 0; i < sz - 1; ++i ){ int key = target - numbers[i]; int j = biSearch( numbers, i + 1, sz - 1, key ); if(-1 == j) continue; ret.push_back(i+1); ret.push_back(j+1); return ret; } return ret; }private: int biSearch( const vector<int>& arr, int low, int high, int key ){ while(low <= high){ int mid = (low+high)/2; if(arr[mid] == key) return mid; else if( key < arr[mid] ) high = mid - 1; else low = mid + 1; } return -1; }};
0 0
- leetcode-167-Input array is sorted
- leetcode 167: Two Sum II - Input array is sorted
- Leetcode NO.167 Two Sum II - Input array is sorted
- [leetcode 167] Two Sum II - Input array is sorted
- LeetCode 167: Two Sum II - Input array is sorted
- leetcode 167 Two Sum II - Input array is sorted C++
- LeetCode 167 Two Sum II - Input array is sorted
- LeetCode #167: Two Sum II - Input array is sorted
- LeetCode 167:Two Sum II - Input array is sorted
- LeetCode[167] Two Sum II - Input array is sorted
- Leetcode #167 Two Sum II - Input array is sorted
- Leetcode 167 Two Sum II - Input array is sorted
- leetcode 167 Two Sum II - Input array is sorted
- [LeetCode]167 Two Sum II - Input array is sorted
- LeetCode 167 Two Sum 2-Input array is sorted
- LeetCode: 2 Sum (Input array is sorted)
- leetcode note--leetcode 167 Two Sum II - Input array is sorted
- LeetCode-Two Sum II - Input array is sorted
- 编译行语言与解释型语言
- Leetcode008-String to Integer (atoi)
- 4289: PA2012 Tax
- samba实现ubuntu跟windows文件共享
- C++快速温习笔记(基本)[1]
- leetcode-167-Input array is sorted
- 引导页使用GuideView
- Android 流行框架查速表
- Raft一致性算法
- 【jzoj4964】【Rhyme】【字符串哈希】【拓扑排序】
- js实现简单计时器
- Vim编写程序放到指定文件夹
- 1977: [BeiJing2010组队]次小生成树 Tree
- Java——数组复制