Answers for "two sum solution"

0

two sum problem

vector<int> twoSum(vector<int>& nums, int target) {
    int len = nums.size();
    for(int i = 0; i < len; i++) {
        for(int j = i + 1; j < len; j++) {
            if(nums[j] == target - nums[i])
                return { i, j };
        }
    }
    return {-1, -1};
};
Posted by: Guest on March-04-2022
0

two sum solution

vector<int> twoSum(vector<int> &nums, int target){ // Brute Force Approach
            for(int i = 0; i < nums.size(); i++){
                for(int j = i+1; j < nums.size(); j++){
                    if(nums[i] + nums[j] == target){
                        vector<int> result;
                        result.push_back(i);
                        result.push_back(j);
                        return result;
                    }
                }
            }
            return vector<int>();  // return empty vector if no two sum solution
        }
Posted by: Guest on June-25-2022
0

two sum problem

vector<int> twoSum(vector<int>& nums, int target) {
    int front = 0, rear = nums.size() - 1;
    sort(nums.begin(), nums.end());
    while(front < rear) {
      int sum = nums[front] + nums[rear];
      if (sum == target)
       break;
      else if (sum > target)
       rear--;
      else
       front++;
    }
    return {front, rear};
};
Posted by: Guest on March-04-2022

Browse Popular Code Answers by Language