a stupid O(nlogn) C++ solution beat 95%?


  • 0
    Q
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> result(2);
            result = {0,0};
            vector <int> numscopy = nums;
            sort(numscopy.begin(),numscopy.end());
            auto left = numscopy.begin();
            auto right = numscopy.end()-1;
            while (left != right){
                if (*left + *right <target) left++;
                if (*left + *right >target) right--;
                if (*left + *right == target) {
                    
                    for (auto index = nums.begin();index<nums.end();index++)
                        if (*index == *left) {
                            result[0] = index-nums.begin();
                            break;
                        }
                    for (auto index = nums.begin();index<nums.end();index++)
                        if (*index == *right && index-nums.begin() != result[0]) {
                            result[1] = index-nums.begin();
                            break;
                        }
                    return result;
                }
            }
            return result;
    
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.