First Update

This commit is contained in:
huihut
2018-02-09 21:47:58 +08:00
commit 6b742a5393
11 changed files with 298 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
class Solution {
public:
int maxProfit(vector<int>& prices) {
int left = 0, right = 0;
int max = 0, temp = 0;
for(auto i = 0; i < prices.size(); ++i) {
right = i;
temp = prices[right] - prices[left];
if(temp < 0) left = i;
if(max < temp) max = temp;
}
return max;
}
};

View File

@@ -0,0 +1,22 @@
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0, right = height.size()-1;
int max = 0, temp = 0;
while(left < right) {
temp = (right - left) * (height[left] < height[right] ? height[left] : height[right]);
if(max < temp) max = temp;
if(height[left] < height[right]) {
do{
left++;
} while(left < right && height[left-1] >= height[left]);
}
else {
do{
right--;
} while(left < right && height[right] <= height[right+1]);
}
}
return max;
}
};

View File

@@ -0,0 +1,26 @@
#include <map>
class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
map<int, int> m_times;
int moreThanTimes = n / 2;
for (auto i = 0; i < n; ++i) {
auto it = m_times.find(nums[i]);
if (it == m_times.end()) {
// No existence in map, insert
m_times.insert(std::pair<int, int>(nums[i], 1));
it = m_times.find(nums[i]);
}
// Is it more than ⌊ n/2 ⌋ times ?
if ((*it).second > moreThanTimes) {
return (*it).first;
}
else {
(*it).second++;
}
}
// Can't find
return -1;
}
};

View File

@@ -0,0 +1,13 @@
#define MIN_INT -2147483648
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max = MIN_INT, temp = 0;
for(auto i = 0; i < nums.size(); ++i) {
temp += nums[i];
if(temp > max) max = temp;
if(temp < 0) temp = 0;
}
return max;
}
};

View File

View File

@@ -0,0 +1,12 @@
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int left = 0, right = 0;
for(; left < nums.size() && nums[left] != 0; left++);
for(right = left; right < nums.size(); right++) {
if(nums[right] == 0) continue;
nums[left++] = nums[right];
}
while(left < nums.size()) nums[left++] = 0;
}
};

View File

@@ -0,0 +1,18 @@
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> sum;
for(auto i = 0; i < nums.size(); i++)
{
for(auto j = i+1; j < nums.size(); j++)
{
if(i == j) continue;
if(nums[i] + nums[j] != target) continue;
sum.push_back(i);
sum.push_back(j);
return sum;
}
}
return sum;
}
};