75. Sort Colors
Given an array with n objects colored red, white or blue, sort them in-place 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.
Note: You are not suppose to use the library’s sort function for this problem.
Example:
1 | Input: [2,0,2,1,1,0] |
Follow up:
- A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s. - Could you come up with a one-pass algorithm using only constant space?
1 | class Solution { |
88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
1 | Input: |
1 | class Solution { |
189. Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Example 1:
1 | Input: nums = [1,2,3,4,5,6,7], k = 3 |
Example 2:
1 | Input: nums = [-1,-100,3,99], k = 2 |
Constraints:
1 <= nums.length <= 2 * 10^4
- It’s guaranteed that
nums[i]
fits in a 32 bit-signed integer. k >= 0
1 | // time O(n),虽然三次翻转,但是没有累乘的操作 |
41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
1 | Input: [1,2,0] |
Example 2:
1 | Input: [3,4,-1,1] |
Example 3:
1 | Input: [7,8,9,11,12] |
Note:
Your algorithm should run in O(n) time and uses constant extra space.
1 | //Bucket Sort |