LeetCode #151 Two Sum

# LeetCode #151 Two Sum

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

代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> temp = numbers;
        sort(temp.begin(), temp.end());
        //cout<<*numbers.begin()<<numbers.at(3)<<endl;
        int index1,index2;
        int i = 0,j = temp.size()-1;
        while(i < j){
        //cout<<i<<j<<endl;
        int sum = temp[i] + temp[j];
        if(sum == target){
            break;
        }else if(sum > target){
            j--;
        }else{
            i++;
        }
    

        for(int k = 0; k < temp.size(); k++){
            if(numbers[k] == temp[i])
                {index1 = k+1;break;}
        }
        for(int k = temp.size()-1; k >= 0; k--){
            //cout<<k<<endl;
            if(numbers[k] == temp[j])
                {index2 = k+1;break;}
        }
        if(index1 > index2){
            int temp = index1;
            index1 = index2;
            index2 = temp;
        }
        vector<int> result;
        result.push_back(index1);
        result.push_back(index2);
        return result;
    }
};

int main()
{
    //cout << "Hello world!" << endl;
    int nums[4] = {4,3,2,1};
    vector<int> numbers(&nums[0], &nums[4]);
    Solution solution;
    vector<int> re = solution.twoSum(numbers, 5);
    cout<<re.at(0)<<" "<<re.at(1);
    return 0;
}

总结:

  • 一开始什么也没考虑写了个二重循环,结果时间超限
  • 看了解析之后重写,结果忘记考虑 index1 < index2 WA了
  • 之后又加了个判断才AC
  • 时间复杂度O(nlogn) 还有个O(n)的解,要用map,以后写

转载于:https://www.cnblogs.com/Haeckel/p/3893392.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值