LC27. Remove Element
從一個數組里刪除指定的數。。。隨便就AC了,就不寫了。。。騙傻子的題。
LC18. 4 Sum
與上一篇的2Sum和3Sum同類型,求所有相加等于0的四個數的組合。
思路一樣的。先排序,然后夾逼。沒什么坑,不細說了。
代碼:
class Solution {
public:
vector<vector<int> > fourSum(vector<int>& nums, int target)
{
vector<vector<int> > result;
if(nums.size() < 4)
return result;
sort(nums.begin(), nums.end());
auto last = nums.end();
for(auto a = nums.begin(); a < prev(last, 3); ++a)
{
for(auto b = next(a); b < prev(last, 2); ++b)
{
auto c = next(b);
auto d = prev(last);
while(c < d) //要始終保證c<d
{
if( *a + *b + *c + *d < target)
++c;
else if( *a + *b + *c + *d > target)
--d;
else
{
result.push_back({ *a, *b, *c, *d });
++c;
--d;
}
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
LC31. Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
這道題一開始連題目都沒看懂,然后當然就是谷歌啦,啊不對,百度,谷歌是啥?
全排列,就是一組數的所有排列組合。1,2,3
的排列有:
1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1
比如例子里面的1,2,3 → 1,3,2
,很顯然123的下一個排列就是132。如果當前排列是所有排列中的最后一種,則下一個排列返回到第一個排列,如:3,2,1 → 1,2,3
。
理解了這個之后,算法思想并不難。先用人話寫一下:
1. 從右向左,尋找第一個打破遞增規律的數字,記做Partition。
2. 從右向左,尋找第一個大于分割數的數字,記做Change。
3. 調換Partition和Change。
4. 將調換后的Partition所在位置后面的數置為倒序。
算法很簡單,但實現目前寫不出來,這道題就當沒做過,回頭重做。
無關內容
去除連續空格:
// remove consecutive spaces
std::string s = "wanna go to space?";
auto end = std::unique(s.begin(), s.end(), [](char l, char r){
return std::isspace(l) && std::isspace(r) && l == r;
});
兩個函數:
bind1st(const Operation& op, const T& x)
就是這么一個操作:x op value
,而bind2nd(const Operation& op, const T& x)
就是這么一個操作:value op x
,其中value是被應用bind的對象。
好了,今天就學了這么一點,不能學太多,不然沒法保持渣渣的水平了。