LeetCode实战练习题目 - Array
Posted insist钢
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode实战练习题目 - Array相关的知识,希望对你有一定的参考价值。
实战练习题目 - Array
class Solution {
public:
int maxArea(vector<int>& height) {
int res = 0;
int i = 0;
int j = height.size() - 1;
while (i < j) {
int area = (j - i) * min(height[i], height[j]);
res = max(res, area);
if (height[i] < height[j]) {
i++;
} else {
j--;
}
}
return res;
}
};
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int numZeroes = 0;
for (int i = 0; i < n; i++) {
numZeroes += (nums[i] == 0);
}
vector<int> ans;
for (int i = 0; i < n; i++) {
if (nums[i] != 0) {
ans.push_back(nums[i]);
}
}
while (numZeroes--) {
ans.push_back(0);
}
for (int i = 0; i < n; i++) {
nums[i] = ans[i];
}
}
};
class Solution {
public:
long long GetCni(int n, int i) {
i = (n - i > i)? i : (n - i);
if(i == 0) return 1;
else return GetCni(n, i-1)*(n-i+1)/i;
}
int climbStairs(int n) {
int i = 0;
int Sum = 0;
while(i <= n/2) {
Sum += GetCni(n-i, i);
i++;
}
return Sum;
}
};
class Solution {
public:
vector<vector<int> > threeSum(vector<int>& nums) {
vector<vector<int> > ret;
vector<int > vtemp;
int len = nums.size();
sort(nums.begin(),nums.end());//sort the input
for(int i=0;i<len-2;i++){
if(i ==0 ||(i>0 && nums[i] != nums[i-1])){
int p1 = i+1, p2 = len-1; // set two pointers
while(p1 < p2){
if(nums[p1] + nums[p2] < -nums[i]){
p1++;
}else if(nums[p1] + nums[p2] == -nums[i]){
if(p1 == i+1){
vector<int > vtemp{nums[i], nums[p1], nums[p2]};
ret.push_back(vtemp);
vtemp.clear();
}else if(nums[p1] != nums[p1-1]){
vector<int > vtemp{nums[i], nums[p1], nums[p2]};
ret.push_back(vtemp);
vtemp.clear();
}
p1++,p2--;
}else{
p2--;
}
}
}
}
return ret;
}
};
以上是关于LeetCode实战练习题目 - Array的主要内容,如果未能解决你的问题,请参考以下文章