力扣---2020.6.10

9. 回文数

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0){
            return false;
        }
        int y = x;
        int n = 0;
        while(x>0){
            n = n*10 + x%10; 
            x = x/10;
        }
        return n==y;
    }
}
class Solution {
    public boolean isPalindrome(int x) {
        String str = new StringBuilder(String.valueOf(x)).reverse().toString();
        return str.equals(String.valueOf(x));
    }
}

面试题 17.21. 直方图的水量

class Solution {
    public int trap(int[] height) {
        int ans = 0;
        Stack<Integer> stack = new Stack<>();
        for(int i = 0;i<height.length;i++){
            while(!stack.isEmpty() && height[stack.peek()] < height[i]){
                int currHeight = stack.pop();
                while(!stack.isEmpty() && height[stack.peek()]==height[currHeight]){
                    stack.pop();
                }
                if(!stack.isEmpty()){
                    ans += (Math.min(height[stack.peek()],height[i]) - height[currHeight]) * (i-stack.peek()-1);
                }

            }
            stack.add(i);
        }
        return ans;
    }
}

面试题 03.02. 栈的最小值

class MinStack {
    
    int min = Integer.MAX_VALUE;
    Stack<Integer> valStack = new Stack<>();
    Stack<Integer> minStack = new Stack<>();

    /** initialize your data structure here. */
    public MinStack() {

    }
    
    public void push(int x) {
        min = Math.min(min, x);
        valStack.push(x);
        minStack.push(min);
    }
    
    public void pop() {
        valStack.pop();
        minStack.pop();
        if (minStack.isEmpty()) {
            min = Integer.MAX_VALUE;
        } else {
            min = minStack.peek();  
        }
    }
    
    public int top() {
        return valStack.peek();
    }
    
    public int getMin() {
        return min;
    }
}

你知道的越多,你不知道的越多。

你可能感兴趣的:(数据结构与算法)