您的位置:首页 > 其它

189. Rotate Array \ 169. Majority Element \ Best time to buy

2017-01-18 17:20 489 查看
Rotate Array

Majority Element

Best time to buy

189. Rotate Array

法一:

class Solution {
public:
void rotate(vector<int>& nums, int k) {
queue<int> tmp;
k = k%nums.size();
k = nums.size() - k;

for(int i = 0; i < k; i++)
{
tmp.push(nums[i]);
}
nums.erase(nums.begin(), nums.begin() + k);

while(!tmp.empty())
{
int t = tmp.front();
tmp.pop();
nums.push_back(t);
}
}
};


法二:

class Solution
{
public:
void rotate(int nums[], int n, int k)
{
if ((n == 0) || (k <= 0))
{
return;
}

// Make a copy of nums
vector<int> numsCopy(n);
for (int i = 0; i < n; i++)
{
numsCopy[i] = nums[i];
}

// Rotate the elements.
for (int i = 0; i < n; i++)
{
nums[(i + k)%n] = numsCopy[i];
}
}
};


法二:

class Solution
{
public:
void rotate(int nums[], int n, int k)
{
if ((n == 0) || (k <= 0))
{
return;
}

int cntRotated = 0;
int start = 0;
int curr = 0;
int numToBeRotated = nums[0];
int tmp = 0;
// Keep rotating the elements until we have rotated n
// different elements.
while (cntRotated < n)
{
do
{
tmp = nums[(curr + k)%n];
nums[(curr+k)%n] = numToBeRotated;
numToBeRotated = tmp;
curr = (curr + k)%n;
cntRotated++;
} while (curr != start);
// Stop rotating the elements when we finish one cycle,
// i.e., we return to start.

// Move to next element to start a new cycle.
start++;
curr = start;
numToBeRotated = nums[curr];
}
}
};


169. Majority Element

法一:

class Solution {
public:
int majorityElement(vector<int>& nums) {
int nums_len = nums.size();
int result = 0;
int max_times = 0;
map<int, int> counter;

for(int i = 0; i < nums_len; i++)
{
if(counter.count(nums[i]) > 0)
{
counter[nums[i]]++;
if(counter[nums[i]] > max_times)
{
result = nums[i];
max_times = counter[nums[i]];
}
}
else
{
counter[nums[i]] = 1;
if(counter[nums[i]] > max_times)
{
result = nums[i];
max_times = counter[nums[i]];
}
}
}

return result;
}
};


法二:使用 Moore’s voting algorithm。

int majorityElement(vector<int> &num) {
int majorityIndex = 0;
for (int count = 1, i = 1; i < num.size(); i++) {
num[majorityIndex] == num[i] ? count++ : count--;
if (count == 0) {
majorityIndex = i;
count = 1;
}
}

return num[majorityIndex];
}


Moore’s Voting Algorithm 介绍:

http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html

Best time to buy

法一:

class Solution {
public:
int maxProfit(vector<int>& prices) {
int prices_len = prices.size();
int profit_max = 0;

for(int i = 0; i < prices_len - 1; i++)
{
for(int j = i + 1; j < prices_len; j++)
{
int profit_tmp = prices[j] - prices[i];
profit_max = profit_tmp > profit_max? profit_tmp : profit_max;
}
}

return profit_max;
}
};


法二:

class Solution {
public:
int maxProfit(vector<int> &prices) {
int maxPro = 0;
int minPrice = INT_MAX;

for(int i = 0; i < prices.size(); i++){
minPrice = min(minPrice, prices[i]);
maxPro = max(maxPro, prices[i] - minPrice);
}

return maxPro;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 189 169 vector easy