A 16ms C++ Solution Using another vector


  • 9
    C
    class Solution
    {
    public:
        vector<int> twoSum(vector<int>& numbers, int target)
        {
            vector<int> tmpNumbers(numbers.begin(), numbers.end());
            sort(tmpNumbers.begin(), tmpNumbers.end());
    
            int val1 = -1;
            int val2 = -1;
            int i = 0;
            int j = tmpNumbers.size() - 1;
            // find two numbers added equals to target
            while(i < j)
            {
                if((tmpNumbers[i] + tmpNumbers[j]) < target)
                {
                    i++;
                }
                else if((tmpNumbers[i] + tmpNumbers[j]) > target)
                {
                    j--;
                }
                else
                {
                    val1 = tmpNumbers[i];
                    val2 = tmpNumbers[j];
                    break;
                }
            }
    
            vector<int> result;
            // find the index of the two numbers
            for(int i = 0; i < numbers.size(); i++)
            {
                if(numbers[i] == val1 || numbers[i] == val2)
                {
                    result.push_back(i + 1);
                }
                if(2 == result.size())
                {
                    return result;
                }
            }
            return result;
        }
    };

  • 0
    F

    i like the answer than so called "unordered_map Jesus"


Log in to reply
 

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