【題解】LeetCode 1. Two Sum

題目敘述:https://leetcode.com/problems/two-sum/
解題想法:Two Pointers【筆記

  • 題目要求回傳的答案是indices。使用【方法1】時需對index額外處理。不然排序後順序會亂掉。

【方法1】Two Pointers (8ms)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<pair<int,int> > check;
        for (int i=0; i<nums.size(); i++){
            check.push_back({nums[i], i});
        }
        sort(check.begin(), check.end());
        vector<int> ans;
        int l = 0;
        int r = (int)nums.size() - 1;
        while (l < r){
            if (check[l].first + check[r].first > target) r--;
            else if (check[l].first + check[r].first < target) l++;
            else {
                ans.push_back(check[l].second);
                ans.push_back(check[r].second);
                break;
            }
        }
        return ans;
    }
};

【方法2】暴力枚舉 (200ms)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int check;
        vector<int> ans;
        for (int i=0; i<nums.size()-1; i++){
            check = target - nums[i];
            for (int j=i+1; j<nums.size(); j++){
                if (nums[j] == check){
                    ans.push_back(i);
                    ans.push_back(j);
                }
            }
            if (ans.size()) break;
        }
        return ans;
    }
};
分享本文 Share with friends