• leetcode学习01


    常用数组操作

    //创建数组
    //方法1
    int[] a = {1,2,3};
    //方法2 
    int[] b = new int[]{1,2,3};
    //方法3
    int[] c = new int[3];
    for(int i=0;i<a.length;i++){
        c[i] = i+1;
    }
    //方法4
    ArrayList<Integer> arr = new ArrayList<>();
    for(int i=0;i<3;i++){
        arr.add(i+1);
    }
    //添加元素
    arr.add(99);//[1,2,3,99] 时间复杂度O(1)
    arr.add(3,88);//[1,2,3,88,99]  时间复杂度O(n)
    
    //访问元素,通过下标索引访问,时间复杂度O(1)
    int c1 = c[1];
    int arr1 = arr.get(1);
    
    //更新元素,时间复杂度O(1)
    c[1] = 11;
    arr.set(1,11);
    
    //删除元素,时间复杂度O(n)
    arr.remove(3);
    
    //数组的长度,时间复杂度O(1)
    int cSize = c.length;
    int arrSize = arr.size();
    
    //遍历数组 时间复杂度O(n)
    for(int i=0;i<c.length;i++){
        int current = c[i];
        System.out.println("c at index"+i+":"+current);
    }
    for(int i=0;i<arr.size();i++){
        int current = arr.get(i);
         System.out.println("arr at index"+i+":"+current);
    }
    
    //查找元素 时间复杂度O(n)
    for(int i=0;i<c.length;i++){
        if(c[i]==99){
            System.out.println("we found 99 in c");
        }
    }
    boolean is99 = arr.contains(99);
    System.out.println("Are we found 99 in arr?"+is99);
    }
    
    //数组从小到大排序 时间复杂度O(NlogN)
    c = new int[]{2,3,1};
    Arrays.sort(c);
    
    arr = new ArrayList<>();
    arr.add(2);
    arr.add(3);
    arr.add(1);
    Collections.sort(arr);
    //从大到小排序
    Collections.sort(arr,Collections.reverseOrder());//用array创建的话

    LeetCode数组

    485 最大连续1的个数

    给定一个二进制数组, 计算其中最大连续 1 的个数。

    示例:

    输入:[1,1,0,1,1,1]
    输出:3
    解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.

    //设置两个变量,每遇到1,count+1,当遇到0,result赋值为count和result比较的最大值,同时count清0
    //最后返回最大值
    class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            if(nums==null || nums.length==0){
                return 0;
            }
            int count = 0;
            int result = 0;
            for(int i=0;i<nums.length;i++){
                if(nums[i]==1){
                    count++;
                }else{
                    result = Math.max(result,count);
                    count=0;
                }
            }
            return Math.max(result,count);
        }
    }

    283 移动零

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

    示例:

    输入: [0,1,0,3,12] 输出: [1,3,12,0,0]

    说明:

    必须在原数组上操作,不能拷贝额外的数组。
    尽量减少操作次数。

    //遍历数组,把所有非零数移到前面的位置
    class Solution {
        public void moveZeroes(int[] nums) {
          int index = 0;
          for(int i=0;i<nums.length;i++){
              if(nums[i]!=0){
                   nums[index] = nums[i];
              index++;
              }
          }
          for(int i=index;i<nums.length;i++){
              nums[i]=0;
          }
        }
    }

    27移除元素

    给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。

    不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。

    元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

    示例 1:

    输入:nums = [3,2,2,3], val = 3 输出:2, nums = [2,2]

    解释:函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。你不需要考虑数组中超出新长度后面的元素。

    例如,函数返回的新长度为 2 ,而 nums = [2,2,3,3] 或 nums = [2,2,0,0],也会被视作正确答案。

    //双指针,一个指针从前往后找,找到val停下
    //一个指针从后往前找,找不到val停下
    //指针所指元素交换位置
    class Solution {
        public int removeElement(int[] nums, int val) {
          if(nums==null || nums.length==0){
              return 0;
          }
          int l=0;
          int r=nums.length-1;
          while(l<r){
              while(l<r && nums[l]!=val){
                  l++;
              }
              while(l<r && nums[r]==val){
                  r--;
              }
              int temp = nums[l];
              nums[l] = nums[r];
              nums[r] = temp;
          }
          return nums[l] == val? l:l+1;
        }
    
    }

    常用链表操作

    //创建链表
    LinkedList<Integer> list = new LinkedList<>();
    //添加元素
    list.add(1);
    list.add(2);
    list.add(3);
    //[1,2,3]
    list.add(2,99);
    //[1,2,99,3]
    
    //访问元素,返回元素
    int element = list.get(2)
    //搜索元素,返回索引
    int index = list.indexof(99);
    //更新元素
    list.set(2,88);//[1,2,88,3]
    //删除元素
    list.remove(2);//[1,2,3]
    //长度
    int length = list.size();//3

    LeetCode链表

    203 移除链表元素

    给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

    输入:head = [1,2,6,3,4,5,6], val = 6
    输出:[1,2,3,4,5]

    class Solution {
        public ListNode removeElements(ListNode head, int val) {
          ListNode dummy = new ListNode(0);
          dummy.next = head;
          ListNode prev = dummy;
          while(head!=null){
              if(head.val==val){
                  prev.next = head.next;
              }else{
                  prev = head;
              }
              head = head.next;
          }
          return dummy.next;
        }
    }

    206 反转链表

    给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

    输入:head = [1,2,3,4,5]
    输出:[5,4,3,2,1]

    class Solution {
        public ListNode reverseList(ListNode head) {
          ListNode dummy = new ListNode(0);
          dummy.next = head;
          while(head!=null&&head.next!=null){
              ListNode dnext = dummy.next;
              ListNode hnext = head.next;
              dummy.next = hnext;
              head.next = hnext.next;
              hnext.next = dnext;
          }
          return dummy.next;
        }
    }

    常用队列操作

    //创建队列
    Queue<Integer> queue = new LinkedList<>();
    //添加 [1,2,3]
    queue.add(1);
    queue.add(2);
    queue.add(3);
    //获取即将出队的元素
    int temp1 = queue.peek();//1
    //删除即将出队的元素
    int temp2 = queue.poll();
    //判断队列是否为空
    System.out.println(queue.isEmpty());
    //队列长度
    System.out.println(queue.size());
    //遍历队列 边删除边遍历
    while(!queue.isEmpty()){
        int temp = queue.poll();
        System.out.println(temp);
    }

    LeetCode队列

    933最近的请求次数

    写一个 RecentCounter 类来计算特定时间范围内最近的请求。

    请你实现 RecentCounter 类:

    RecentCounter() 初始化计数器,请求数为 0 。
    int ping(int t) 在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t] 内发生的请求数。

    保证 每次对 ping 的调用都使用比之前更大的 t 值。

    示例:

    输入: ["RecentCounter", "ping", "ping", "ping", "ping"] [[], [1], [100], [3001], [3002]] 输出: [null, 1, 2, 3, 3]

    class RecentCounter {
        Queue<Integer> queue;
    
        public RecentCounter() {
           queue = new LinkedList<>();
        }
        
        public int ping(int t) {
           queue.add(t);
           while(!queue.isEmpty() && t-queue.peek()>3000){
               queue.poll();
           }
           return queue.size();
        }
    }

    常用栈操作

    //创建栈
    Stack<Integer> stack = new Stack<>();
    //添加元素
    stack.push(1);
    stack.push(2);
    stack.push(3);
    //获取栈顶元素
    stack.peek();
    //删除栈顶元素
    int temp = stack.pop();
    //栈大小
    stack.size();
    //栈是否为空
    stack.isEmpty();
    //栈的遍历,边删除边遍历
    while(!stack.isEmpty()){
        int num = stack.pop();
        System.out.println(num);
    }

    LeetCode栈

    20有效的括号

    给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

    有效字符串需满足:

    左括号必须用相同类型的右括号闭合。
    左括号必须以正确的顺序闭合。

    示例 1:

    输入:s = "()" 输出:true



    class Solution {
        public boolean isValid(String s) {
          if(s.length()==0){
              return true;
          }
          Stack<Character> stack = new Stack<>();
          for(char ch: s.toCharArray()){
              if(ch=='('||ch=='{'||ch=='['){
                  stack.push(ch);
              }else{
                  if(stack.isEmpty()){
                      return false;
                  }else{
                      char temp = stack.pop();
                      if(ch==')'){
                          if(temp!='('){
                              return false;
                          }
                      }else if(ch=='}'){
                          if(temp!='{'){
                              return false;
                          }
                      }else if(ch==']'){
                          if(temp!='['){
                              return false;
                          }
                      }
                  }
              }
          }
          return stack.isEmpty()? true : false;
        }
    }

    496下一个更大元素

    给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。

    请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。

    nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。

    示例 1:

    输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1]

    class Solution {//创建两个栈
        public int[] nextGreaterElement(int[] nums1, int[] nums2) {
            int[] res = new int[nums1.length];
            Stack<Integer> stack = new Stack<>();
            for(int num:nums2){
                stack.push(num);
            }
            for(int i = 0;i<nums1.length;i++){
                Stack<Integer> temp = new Stack<>();
                boolean isFound = false;
                int cur = nums1[i];
                int max = -1;
                while(!stack.isEmpty()&&!isFound){
                    int top = stack.pop();
                    if(top>cur){
                        max=top;
                    }else if(top==cur){
                        isFound=true;
                    }
                   temp.push(top); 
                }
                res[i]=max;
                while(!temp.isEmpty()){
                    stack.push(temp.pop());
                }
            }
            return res;
        }
    }

    常用哈希表操作

    //创建哈希表
    String[] hashTable = new String[4];//数组存放
    HashMap<Integer,String> map = new HashMap<>();
    //添加元素
    hashTable[1] = "hanmeimei";
    hashTable[2] = "xiaohong";
    hashTable[1] = "xiaoming";
    map.put(1,"hanmeimei");
    map.put(2,"xiaohong");
    map.put(3,"xiaoming");
    //更新元素
    hashTable[1] = "bitch";
    map.put(1,"bitch");
    //删除元素
    hashTable[1] = "";
    map.remove(1);
    //获取元素
    String temp = hashTable[3];
    map.get(3);
    //检查key存在
    map.containKey(3);
    //长度,是否还有元素
    map.size();
    map.isEmpty();

    LeetCode哈希表

    217存在重复元素

    给定一个整数数组,判断是否存在重复元素。

    如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。

    示例 1:

    输入: [1,2,3,1] 输出: true

    class Solution {
        public boolean containsDuplicate(int[] nums) {
           if(nums == null || nums.length ==0){
               return false;
           }
           HashMap<Integer,Integer> map = new HashMap<>();
           for(int num : nums){
               if(map.containsKey(num)){
                   map.put(num,map.get(num)+1);
               }else{
                   map.put(num,1);
               }
           }
           for(int k : map.keySet()){
               if(map.get(k)>1){
                   return true;
               }
           }
           return false;
        }
    }

    389找不同

    给定两个字符串 s 和 t,它们只包含小写字母。

    字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

    请找出在 t 中被添加的字母。

    示例 1:

    输入:s = "abcd", t = "abcde" 输出:"e" 解释:'e' 是那个被添加的字母。

    class Solution {
        public char findTheDifference(String s, String t) {
           int sizeS = s.length();
           int sizeT = t.length();
           if(sizeS==0){
               return t.charAt(0);
           }
           int[] table = new int[26];
           for(int i=0;i<sizeT;i++){
               if(i<sizeS){
                   table[s.charAt(i)-'a']++;
               }
               table[t.charAt(i)-'a']--;
           }
           for(int i=0;i<26;i++){
               if(table[i]!=0){
                   return (char)('a'+i);
               }
           }
           return 'a';
        }
    }

    496下一个更大元素

    输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1]

    //栈+哈希表
    class Solution {
        public int[] nextGreaterElement(int[] nums1, int[] nums2) {
            int[] res = new int[nums1.length];
            Stack<Integer> stack = new Stack<>();
            HashMap<Integer,Integer> map = new HashMap<>();
            for(int num:nums2){
                while(!stack.isEmpty()&& num>stack.peek()){
                    int temp = stack.pop();
                    map.put(temp,num);
                }
                stack.push(num);
            }
            while(!stack.isEmpty()){
                map.put(stack.pop(),-1);
            }
            for(int i=0;i<nums1.length;i++){
                res[i]=map.get(nums1[i]);
            }
            return res;
        }
    }

    常用哈希集合操作

    //创建
    HashSet<Integer> set = new HashSet<>();
    //添加元素 
    set.add(10)
    //搜索元素 0(1)
    set.contains(2);
    //删除元素 0(1)
    set.remove(2);
    //长度 0(1)
    set.size();

    LeetCode集合

    217存在重复元素

    class Solution {
        public boolean containsDuplicate(int[] nums) {
           if(nums==null||nums.length==0){
               return false;
           }
           HashSet<Integer> set = new HashSet<>();
           for(int num : nums){
               set.add(num);
           }
           return set.size()==nums.length? false : true;
        }
    }

    705设计哈希集合

    使用任何内建的哈希表库设计一个哈希集合(HashSet)。

    实现 MyHashSet 类:

    void add(key) 向哈希集合中插入值 key 。
    bool contains(key) 返回哈希集合中是否存在这个值 key 。
    void remove(key) 将给定值 key 从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。

    示例:

    输入: ["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"] [[], [1], [2], [1], [3], [2], [2], [2], [2]] 输出: [null, null, null, true, false, null, true, null, false]

    解释:

    MyHashSet myHashSet = new MyHashSet();

    myHashSet.add(1); // set = [1]

    myHashSet.add(2); // set = [1, 2]

    myHashSet.contains(1); // 返回 True

    myHashSet.contains(3); // 返回 False ,(未找到)

    myHashSet.add(2); // set = [1, 2]

    myHashSet.contains(2); // 返回 True

    myHashSet.remove(2); // set = [1]

    myHashSet.contains(2); // 返回 False ,(已移除)

    class MyHashSet {
        boolean[] hashSet = null;
    
        /** Initialize your data structure here. */
        public MyHashSet() {
           hashSet = new boolean[1000001];
        }
        
        public void add(int key) {
           hashSet[key] = true;
        }
        
        public void remove(int key) {
           hashSet[key] = false;
        }
        
        /** Returns true if this set contains the specified element */
        public boolean contains(int key) {
            return hashSet[key];
        }
    }

     

  • 相关阅读:
    【转】Ubuntu 20.04修改ip地址
    试用 Portable Allegro Serve
    看完了 Source Code
    Common Lisp 参数传递的几种形式
    Irony 一个 .NET 语言实现工具包
    PPT 技巧学习
    LISP 练习:quick sort
    关于 Business Rule Engine
    转换 PDF 格式为适合电纸书阅读的版本
    IIS 7 SMTP configuration
  • 原文地址:https://www.cnblogs.com/asako/p/14782931.html
Copyright © 2020-2023  润新知