34. 在排序数组中查找元素的第一个和最后一个位置 (中等)
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:
输入:nums = [], target = 0
输出:[-1,-1]
二分
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.empty())
return vector<int>{-1, -1};
int l = 0, r = nums.size() - 1, m;
while(l <= r)
{
m = (l + r) / 2;
if(nums[m] == target)
break;
else if(nums[m] > target)
{
r = m - 1;
}
else
l = m + 1;
}
l = m, r = m;
if(nums[m] != target)
return vector<int>{-1, -1};
else
{
while(l >= 0 && nums[l] == target)
l--;
while(r < nums.size() && nums[r] == target)
r++;
return vector<int>{l+1,r-1};
}
}
};
35. 搜索插入位置 (简单)
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
二分法
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1, m;
while(l <= r)
{
m = (l + r) / 2;
if(nums[m] == target)
return m;
else if(nums[m] < target)
l = m + 1;
else r = m - 1;
}
return l;
}
};
36. 有效的数独 (中等)
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
- 数字 1-9 在每一行只能出现一次。
- 数字 1-9 在每一列只能出现一次。
- 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
示例 1:
输入:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
输出: true
说明:
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
给定数独序列只包含数字 1-9 和字符 '.' 。
给定数独永远是 9x9 形式的。
3X3的序号如下:box_id = i/3*3 + j/3。 一次遍历,考虑行、列、3x3情况。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool col[9][9] = {false};
bool row[9][9] = {false};
bool boxes[9][9] = {false};
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
if(board[i][j] == '.')
continue;
int num = board[i][j] - '1'; //board为char,所以是减去“1”
int box = i /3 * 3 + j /3;
if(col[i][num] | row[j][num] | boxes[box][num])
return false;
col[i][num] = row[j][num] = boxes[box][num] = true;
}
return true;
}
};