Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
How to convert this Java code to C++ code?
Java
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length() - 1;
while(left < right) {
int sum = numbers[left] + numbers[right];
if(sum == target) return new int[] {left +1, right + 1};
else if(sum > target) --right;
else ++left;
}
}
}
C++
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int
target) {
// vector<vector <int>> res; do we use a 2d
vector?
int left = 0, right = numbers.size() - 1;
while(left < right) {
int sum = numbers[left] + numbers[right];
if(sum == target)
return //is it a 2d vector thing?
else if(sum > target)
--right;
else
++left;
}
return NULL;
}
};
Kindly let me know. Your help will be much appreciated.
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int> numbers, int target) { vector<int> result; int left = 0, right = numbers.size() - 1; while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) { result.push_back(left+1); result.push_back(right+1); return result; } else if (sum > target) --right; else ++left; } return result; } };
Get Answers For Free
Most questions answered within 1 hours.