problem 33,34,35,36,37,38
33. Search in Rotated Sorted Array
Medium
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm’s runtime complexity must be in the order of O(log n).
Example 1:
1 | |
Example 2:
1 | |
从算法复杂度就能看出来是一个二分法
唯一的问题就在于,二分过程中只有一半肯定是顺序的
所以需要加入严谨的判断来解决这种情况
1 | |
34. Find First and Last Position of Element in Sorted Array
Medium
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1:
1 | |
Example 2:
1 | |
1 | |
这里要注意边界的判断,mid=int((low+high)/2),所以mid会接近low bound,所以high=mid是可以的,但是low=mid是不行的,会进入死循环
35. Search Insert Position
Easy
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
1 | |
Example 2:
1 | |
Example 3:
1 | |
Example 4:
1 | |
1 | |
36. Valid Sudoku
Medium
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9without repetition. - Each column must contain the digits
1-9without repetition. - Each of the 9
3x3sub-boxes of the grid must contain the digits1-9without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
Example 1:
1 | |
这个题在于判断是否有重复
1 | |
37. Sudoku Solver
Hard
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
- Each of the digits
1-9must occur exactly once in each row. - Each of the digits
1-9must occur exactly once in each column. - Each of the the digits
1-9must occur exactly once in each of the 93x3sub-boxes of the grid.
Empty cells are indicated by the character '.'.
1 | |
38. Count and Say
Easy
The count-and-say sequence is the sequence of integers with the first five terms as following:
1 | |
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
1 | |
Example 2:
1 | |
1 | |