zoukankan      html  css  js  c++  java
  • 算法练习LeetCode初级算法之设计问题

    • 打乱数组

    不断的让第一个与后面随机选择的数交换

    class Solution {

        private int[] nums;

        private int[] initnums;

    public Solution(int[] nums) {

        this.nums=nums;

        this.initnums=Arrays.copyOf(nums, nums.length);//这里必须要复制,要指明对象

    }

     

    /** Resets the array to its original configuration and return it. */

    public int[] reset() {

        return initnums;//这里返回上面的复制

    }

     

    /** Returns a random shuffling of the array. */

    public int[] shuffle() {

        Random random=new Random();

        for (int i = 0; i <nums.length/2; i++) {

                swap(nums, 0, random.nextInt(nums.length));

            }

        return nums;

    }

    private void swap(int[] nums,int i,int j) {

            int temp=nums[i];

            nums[i]=nums[j];

            nums[j]=temp;

        }

    }

    • 最小栈

    • 自己写的有点慢,勉强通过

      class MinStack {

      /** initialize your data structure here. */

          Stack<Integer> stack;

      public MinStack() {

          stack=new Stack<>();

      }

      public void push(int x) {

      stack.push(x);

      }

      public void pop() {

          if (!stack.isEmpty()) {

                  stack.pop();

              }

      }

      public int top() {

           return stack.peek();//这里和我之前理解的不太一样,之前是取栈顶顺便就删除了

      }

      public int getMin() {

          Stack<Integer> stack2=new Stack<>();

          stack2.addAll(0, stack);

      Collections.sort(stack2);

      return stack2.get(0);

      }

      }

    • 双栈法挺快

      class MinStack {

      /** initialize your data structure here. */

          Stack<Integer> stack,minStack;

      public MinStack() {

          stack=new Stack<>();

          minStack=new Stack<>();

      }

      public void push(int x) {

      stack.push(x);

      if (minStack.isEmpty()) {

                  minStack.push(x);

              }else if (x<=minStack.peek()) {//此处若没有等号

                  minStack.push(x);

              }

      }

      public void pop() {

          if (stack.peek().equals(minStack.peek())) {//这里可能会提示栈为空的异常

              stack.pop();

              minStack.pop();

              }else {

                  stack.pop();

              }

      }

      public int top() {

           return stack.peek();

      }

      public int getMin() {

      return minStack.peek();

      }

      }

  • 相关阅读:
    洛谷 1339 最短路
    洛谷 1330 封锁阳光大学 图论 二分图染色
    洛谷 1262 间谍网络 Tarjan 图论
    洛谷 1373 dp 小a和uim之大逃离 良心题解
    洛谷 1972 莫队
    洛谷 2158 数论 打表 欧拉函数
    洛谷 1414 数论 分解因数 水题
    蒟蒻的省选复习(不如说是noip普及组复习)————连载中
    关于筛法
    关于整数划分的几类问题
  • 原文地址:https://www.cnblogs.com/GavinYGM/p/10375363.html
Copyright © 2011-2022 走看看