A 16ms solution by making a Struct in C++


  • 0
    C
    struct NumStruct
    {
    	NumStruct(int a, int b) : number(a), location(b) {}
    	int number;
    	int location;
    };
    
    bool isLesser(NumStruct a, NumStruct b)
    {
    	return a.number < b.number;
    }
    
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
          	vector<int> resultVec;
    		vector<NumStruct> vecStruct;
    		for (int i = 0; i < nums.size(); ++i)
    		{
    			NumStruct numStruct(nums[i], i);
    			vecStruct.push_back(numStruct);
    		}
    
    		sort(vecStruct.begin(), vecStruct.end(), isLesser);
    		int front = 0;
    		int back = vecStruct.size() - 1;
    
    		while (front != back)
    		{
    			int addResult = (vecStruct[front]).number + (vecStruct[back]).number;
    			if (addResult == target)
    			{
    			int iLocation1 = vecStruct[front].location + 1;
    				int iLocation2 = vecStruct[back].location + 1;
    
    				if (iLocation1 > iLocation2)
    				{
    					int tmp = iLocation1;
    					iLocation1 = iLocation2;
    					iLocation2 = tmp;
    				}
    				resultVec.push_back(iLocation1);
    				resultVec.push_back(iLocation2);
    				return resultVec;
    			}
    			else if (addResult < target )
    			{
    				++front;
    			}
    			else
    			{
    				--back;
    			}
    		}
    		return resultVec;
        }
    };

Log in to reply
 

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