1. 贪心
2.二分查找
2.1 【简单】x 的平方根 (69)
/**
* 二分法
*/
public int mySqrt(int x) {
int l = 0, r = x, ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if ((long) mid * mid <= x) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
2.2 【简单】有效的完全平方数 (367)
/**
* 二分法
*/
public boolean isPerfectSquare(int num) {
int l = 0, r = num;
while (l <= r) {
int mid = l + (r - l) / 2;
if ((long) mid * mid < num) {
l = mid + 1;
} else if ((long) mid * mid > num) {
r = mid - 1;
} else {
return true;
}
}
return false;
}
2.3 【中等】搜索旋转排序数组 (33)
/**
* 首元素与中间元素进行比较,分类讨论
*/
public int search(int[] nums, int target) {
int n = nums.length;
if (n == 0) {
return -1;
}
if (n == 1) {
return nums[0] == target ? 0 : -1;
}
int l = 0, r = n - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] == target) {
return mid;
}
// 中位数先和0元素比较
if (nums[0] <= nums[mid]) {
// 4,5,6,7,0,1,2,3
if (nums[0] <= target && target < nums[mid]) {
r = mid - 1;
} else {
l = mid + 1;
}
} else {
// 6,7,0,1,2,3,4,5
if (nums[mid] < target && target <= nums[n - 1]) {
l = mid + 1;
} else {
r = mid - 1;
}
}
}
return -1;
}
2.4 【中等】搜索二维矩阵 (74)
/**
* 二分法
*/
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int low = 0, high = m * n - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
int x = matrix[mid / n][mid % n];
if (x < target) {
low = mid + 1;
} else if (x > target) {
high = mid - 1;
} else {
return true;
}
}
return false;
}
2.5 【中等】寻找旋转排序数组中的最小值 (153)
/**
* 与一般二分法不同,需要仔细观察记忆。
*/
public int findMin(int[] nums) {
int low = 0;
int high = nums.length - 1;
// 没有等号
while (low < high) {
int pivot = low + (high - low) / 2;
if (nums[pivot] < nums[high]) {
// 不为pivot-1
high = pivot;
} else {
low = pivot + 1;
}
}
return nums[low];
}