27. Remove Element
法一:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
for(vector<int>::iterator it = nums.begin(); it != nums.end();)
{
if(*it == val)
it = nums.erase(it);
else
it++;
}
return nums.size();
}
};
法二:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int cnt = 0;
for(int i = 0 ; i < nums.size() ; ++i) {
if(nums[i] == val)
cnt++;
else
nums[i-cnt] = nums[i];
}
return nums.size()-cnt;
}
};
66. Plus One
法一:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
bool carry = true;
for(int i=digits.size()-1; i >= 0 && carry; i--) {
carry = (++digits[i]%=10) == 0;
}
if(carry) {
digits.insert(digits.begin(), 1);
}
return digits;
}
};
法二:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> result;
int cf = 0;
if(digits.empty())
return result;
int digits_len = digits.size();
digits[digits_len - 1]++;
int tmp;
for(int it = digits_len - 1; it >= 0; it--)
{
tmp = digits[it] + cf;
digits[it] = tmp%10;
cf = tmp/10;
cout << tmp << " " << cf << endl;
}
if(cf)
result.push_back(cf);
for(int i = 0; i < digits_len; i++)
{
result.push_back(digits[i]);
}
return result;
}
};
法一:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int ind_1 = 0;
int ind_last = 0;
std::vector<int>::iterator it;
if(n == 0)
return;
if(m == 0)
{
nums1 = nums2;
return;
}
for(int i = 0; i < n; i++)
{
int nums1_len = nums1.size();
for(ind_1 = ind_last; ind_1 < m + i; ind_1++)
{
if(nums2[i] < nums1[ind_1])
{
it = nums1.begin();
ind_last = ind_1;
nums1.insert(it + ind_last, nums2[i]);
break;
}
else if(ind_1 == m + i - 1)
{
it = nums1.begin();
ind_last = ind_1 + 1;
nums1.insert(it + ind_last, nums2[i]);
break;
}
}
}
//for(int i = 0; i < n; i++)
// nums1.pop_back();
nums1.erase(nums1.begin() + m + n, nums1.begin() + m + (n << 1));
}
};
法二:
while(n>0)
A[m+n-1] = (m==0||B[n-1] > A[m-1]) ? B[--n] : A[--m];
法三:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - 1, j = n - 1, tar = m + n - 1;
while (j >= 0) {
nums1[tar--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
}
}
};
参考链接:
http://blog.csdn.net/zhuimengzh/article/details/6841500