[旧版] LeetCode Two Sum

来源:互联网 发布:窗帘的尺寸怎么算法 编辑:程序博客网 时间:2024/04/29 03:53

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        vector<int> v(numbers);        sort(v.begin(),v.end());        vector<int>::iterator ia = v.begin();        vector<int>::iterator ib = v.end();        int a,b;        ib--;        while(ia < ib) {            if(*ia+*ib > target) {                ib--;            }else if(*ia+*ib < target) {                ia++;            }else {                a = *ia;                b = *ib;                break;            }        }        vector<int> r;        for(int i = 0; i < numbers.size();i++) {            if(numbers[i]==a || numbers[i]==b) {                r.push_back(i+1);            }        }        return r;    }};


思路:暴力解法是O(n^2)。这种解法是O(nlogn)。

关键之处在于排序后首尾指针步进的解法可行,复杂度O(n),算法复杂度为排序复杂度。

最后的for循环查找也很精妙。

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 消防工程师考试题型 助理消防工程师 一级消防工程师论坛 注册消防工程师考试难度 一级消防工程师考试题型 注册二级消防工程师 注册消防工程师论坛 一级注册消防工程师教材 注册消防工程师报名 二级消防工程师考试科目 消防工程师报考条件二级 二级注册消防工程师报考条件 一级注册消防工程师论坛 二级消防工程师好考吗 一级注册消防工程师招聘 注册消防工程师难考吗 考一级消防工程师有用吗 消防工程师难度 一消防工程师 一级消防工程师考试难度 一级消防工程师好考吗 消防工程师待遇 注册消防工程师一级二级区别 一级注册消防工程师好考吗 注册消防工程师好不好考 一级消防工程师难度 二级注册消防工程师考试科目 二级消防考试时间 一级消防工程师招聘 陕西二级消防工程师报名时间 2017消防工程师考试时间 消防工程师代报名 消防技术综合能力 一级注册消防工程师报考条件 河北二级消防工程师报名时间 二级消防工程师报名条件 消防员考试报考条件 消防技术实务 一级注册消防工程师报名时间 消防安全工程师考试时间 消防注册工程师报考条件