剑指 Offer 09. 用两个栈实现队列
思路就是一个栈放元素、另一个栈取元素
class CQueue {
Stack<Integer> s1;
Stack<Integer> s2;
public CQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void appendTail(int value) {
s1.push(value);
}
public int deleteHead() {
if (empty()) return -1;
if (s2.empty()) {
while (!s1.empty())
s2.push(s1.pop());
}
return s2.pop();
}
public boolean empty() {
return s1.empty() && s2.empty();
}
}
剑指 Offer 04. 二维数组中的查找
思路就是从二维数组的左下角或者右上角来二分查找
public boolean findNumberIn2DArray1(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row = matrix.length;
int col = matrix[0].length;
int curRow = 0;
int curCol = col - 1;
while (curRow < row && curCol >= 0) {
if (matrix[curRow][curCol] == target) {
return true;
} else if (matrix[curRow][curCol] > target) {
curCol--;
} else {
curRow++;
}
}
return false;
}
public boolean findNumberIn2DArray2(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row = matrix.length;
int col = matrix[0].length;
int curRow = row - 1;
int curCol = 0;
while (curCol < col && curRow >= 0) {
if (matrix[curRow][curCol] == target) {
return true;
} else if (matrix[curRow][curCol] < target) {
curCol++;
} else {
curRow--;
}
}
return false;
}
剑指 Offer 11. 旋转数组的最小数字
使用二分查找来实现、时间复杂度为O(log2n)、如果数组中的元素都是相同的话、那么时间复杂度就会变为O(n)
public int minArray2(int[] numbers) {
int left = 0;
int right = numbers.length - 1;
while (left < right) {
int mid = (right - left) / 2 + left;
if (numbers[mid] < numbers[right]) {
right = mid;
} else if (numbers[mid] > numbers[right]) {
left = mid + 1;
} else {
right--;
}
}
return numbers[left];
}