13-10-2022
For the array I used two pointers, one for the beginning of the and one for the end of the array. In a loop I checked if sum of those pointer value greater or less than the target value and decrease end pointer or increase start pointer by 1. Otherwise stop the loop.
Returned a vector containing start pointer + 1 and end pointer + 1 as the index in result supposed to start from 1 and not 0.
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res;
int l = 0, h = numbers.size() - 1;
for(int i = 0; i < numbers.size(); i++){
if(numbers[l] + numbers[h] < target){
l++;
}else if(numbers[l] + numbers[h] > target){
h--;
}
else{
res.push_back(l+1);
res.push_back(h+1);
break;
}
}
return res;
}
};
Move Zero
The approach is quite easy and solved it with one go. Firstly, I declared a vector. Then checked if the array contains non-zero, append that that vector otherwise counts how many 0s are there. After the counting is done we just append the number of 0s that was connected. At the end I just replaced the given vector with the new vector. Quite Simple and fun.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
vector<int> res;
int cc = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i] != 0){
res.push_back(nums[i]);
}else{
cc++;
}
}
for(int i = nums.size() - cc; i < nums.size(); i++){
res.push_back(0);
}
nums = res;
}
};
Top comments (0)