34.在排序陣列中查詢元素的第一個和最後一個位置
分析
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums.length < 1) return new int[]{-1, -1};
int num1 = findFirst(nums, target);
int num2 = findLast(nums, target);
return new int[]{num1, num2};
}
public int findFirst(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] == target) right = mid - 1;
else if(nums[mid] > target) right = mid - 1;
else left = mid + 1;
}
if(left < nums.length && nums[left] == target) return left;
return -1;
}
public int findLast(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] == target) left = mid + 1;
else if(nums[mid] > target) right = mid - 1;
else left = mid + 1;
}
if(right >= 0 && nums[right] == target) return right;
return -1;
}
}
36.有效的數獨
分析
class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < 9; i++) {
int rowSum = 0, colSum = 0, sqre = 0;
for(int j = 0; j < 9; j++) {
int r = board[i][j] - 48;
int c = board[j][i] - 48;
int s = board[3 * (i / 3) + j / 3][3 * (i % 3) + j % 3] - 48;
if(r > 0) rowSum = bitCal(rowSum, r);
if(c > 0) colSum = bitCal(colSum, c);
if(s > 0) sqre = bitCal(sqre, s);
if(rowSum == -1 || colSum == -1 || sqre == -1) return false;
}
}
return true;
}
public int bitCal(int val, int n) {
return ((val >> n) & 1) == 1 ? -1 : val ^ (1 < n);
}
}