2020.12.12每日複習

weixin_44460781發表於2020-12-14

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;
    		//不可以直接返回,應該繼續向左邊找,即 [left..mid - 1] 區間裡找
    		if(nums[mid] == target) right = mid - 1;
    		// 應該繼續向右邊找,即 [mid + 1, right] 區間裡找
    		else if(nums[mid] > target) right = mid - 1;
    		// 此時 nums[mid] > target,應該繼續向左邊找,即 [left..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;
    		// 只有這裡不一樣:不可以直接返回,應該繼續向右邊找,即 [mid + 1, right] 區間裡找
    		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);
    }
}