20. Valid Parentheses
Easy
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
1 | Input: "()" |
Example 2:
1 | Input: "()[]{}" |
Example 3:
1 | Input: "(]" |
Example 4:
1 | Input: "([)]" |
Example 5:
1 | Input: "{[]}" |
1 | class Solution { |
26. Remove Duplicates from Sorted Array
Easy
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
1 | Given nums = [1,1,2], |
Example 2:
1 | Given nums = [0,0,1,1,1,2,2,3,3,4], |
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
1 | // nums is passed in by reference. (i.e., without making a copy) |
思路
使用快慢指针来记录遍历的坐标。
- 开始时这两个指针都指向第一个数字
- 如果两个指针指的数字相同,则快指针向前走一步
- 如果不同,则两个指针都向前走一步
- 当快指针走完整个数组后,慢指针当前的坐标加1就是数组中不同数字的个数
关键点解析
双指针
这道题如果不要求,O(n)的时间复杂度, O(1)的空间复杂度的话,会很简单。 但是这道题是要求的,这种题的思路一般都是采用双指针
如果是数据是无序的,就不可以用这种方式了,从这里也可以看出排序在算法中的基础性和重要性。
1 | class Solution { |
88. Merge Sorted Array
Easy
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: |
因为是原地修改所以只能从后向前:
- cur 表示当前要填充的位置,初始化为 m + n - 1
- pm 指向 nums1 的最后一个元素,pn 指向num2 的最后一个元素
- while cur >= 0
- if pm < 0 :将nums2 中剩余的元素插入到 nums1
- if pn < 0 : nums2 中元素已经全部插完,return
- else 选择 nums1[pm] 和 nums2[pn] 中小的插入 nums[cur]
1 | class Solution { |