1 Sort Colors
Given an array with n objects colored red, white or blue, sort them so, objects of the same color is adjacent, with T He colors in the order red, white and blue. Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
There are only 3 numbers to sort, we can use two pointers to iterate over the array, exchange the data with the head pointer when red, the head pointer to 1, the tail pointer to the blue when the data is exchanged, the tail pointer minus 1, and the loop until the end pointer is encountered.
voidSortcolors ( vector<int>& Nums) {intLen = Nums.size ();intBegin =0, end = Len-1; for(inti =0; i<len; i++) {if(I>end)return;if(Nums[i] = =0) {swap (nums[i], nums[begin]); begin++; }Else if(Nums[i] = =2) {swap (nums[i], nums[end]); end--; i--; } } }
2 Combinations
Given-integers n and K, return all possible combinations of k numbers out of 1 ... n.for example,if n = 4 and k = 2, a s Olution is:
[
[2,4],
[3,4],
[2,3],
[+],
[1,3],
[1,4],
]
Choose the number of k from the n number of combinations, we can choose 1, and then from 2 to N to select the number of K-1, select 2, and then from 3 to N to select the number of k-1, in this way to get all the combination.
voidCOMBINEDST (intNintKintLevel vector<int>&res, vector<vector<int>>&result) {if(res.size () = = k) {Result.push_back (res);return; } for(inti = level; i<=n; i++) {res.push_back (i); COMBINEDST (n,k,i+1, Res,result); Res.pop_back (); } } vector<vector<int>>CombineintNintK) { vector<int>Res vector<vector<int> >Resultif(n<k| | k<=0)returnResult COMBINEDST (N,k,1, Res,result);returnResult }
Leetcode's Medium collection (C + + implementation) 14