09、04、11

剑指 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];
    }
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值