classSolution{ publicintsearchInsert(int[] nums, int target){ int l = -1, r = nums.length; while(l + 1 != r) { int m = l + (r - l) / 2; if(nums[m] == target){ return m; } elseif(nums[m] < target){ l = m; } else { r = m; } } return r; } }
classSolution{ publicbooleansearchMatrix(int[][] matrix, int target){ int altitude = -1, latitude = -1; for(int i = 0; i < matrix.length; i++) { if(matrix[i][0] <= target && matrix[i][matrix[i].length - 1] >= target){ altitude = i; latitude = matrix[i].length; } } if(altitude == -1 && latitude == -1) returnfalse; int[] nums = newint[latitude]; for(int i = 0;i < latitude; i++) { nums[i] = matrix[altitude][i]; } int left = -1, right = nums.length; while(left + 1 != right) { int mid = left + ((right - left) >> 1); if(nums[mid] < target) { left = mid; }else { right = mid; } } return nums[right] == target; } }
高手做法,但理解难度更高,空间复杂度更大
classSolution{ publicbooleansearchMatrix(int[][] matrix, int target){ int m = matrix.length, n = matrix[0].length; if (matrix[m-1][n-1] < target) returnfalse; int left = -1, right = m*n; while(left + 1 != right) { int mid = (left + right) >> 1; int i = mid / n; int j = mid % n; if (matrix[i][j] < target) left = mid; else right = mid; } // 最后的结果是right return matrix[right/n][right%n] == target; } }