75. Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
int p = 0,q = n-1;
for(int i=0;i<n;i++) //从左往右扫
{
if(nums[i]==0)
{
swap(nums[i],nums[p]);
p++;
}
}
for(int j=n-1;j>=0;j--) //从右往左扫
{
if(nums[j]==2)
{
swap(nums[j],nums[q]);
q--;
}
}
return;
}
};
135. Candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> rec(n,1);
for(int i=1;i<n;i++)
{
if(ratings[i]>ratings[i-1]&&rec[i]<=rec[i-1])
rec[i] = rec[i-1]+1;
}
for(int j=n-2;j>=0;j--)
{
if(ratings[j]>ratings[j+1]&&rec[j]<=rec[j+1])
rec[j] = rec[j+1]+1;
}
int sum = 0;
for(int i=0;i<n;i++)
{
sum += rec[i];
cout<<rec[i]<<endl;
}
return sum;
}
};
3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
int maxLen = 0;
int i=0,j=0;
while(i<n&&j<n)
{
if(isSingle(s,i,j))
j++;
else
i++;
maxLen = max(maxLen,j-i);
}
return maxLen;
}
bool isSingle(string str,int i,int j)
{
vector<int> hash(256,0);
if(i>j)
return false;
for(int k=i;k<=j;k++)
{
if(hash[str[k]]==0)
hash[str[k]]++;
else
return false;
}
return true;
}
};
网友评论