zoukankan      html  css  js  c++  java
  • 30-Day Leetcoding Challenge Day7

    三种解法:

    第一种是在数组中查找O(n^2)

    第二种是在HashSet中查找O(n)

    第三种是在有序数组中查找O(nlogn)

    JAVA

    class Solution {
        public int countElements(int[] arr) {
            int res = 0;
            for(int i = 0; i < arr.length; i++){
                int cur = arr[i]+1;
                for(int j = 0; j < arr.length; j++){
                    if(cur == arr[j]){
                        res++;
                        break; //!!!bug
                    }
                }
            }
            return res;
        }
    }
    class Solution {
        public int countElements(int[] arr) {
            Set<Integer> set = new HashSet<>();
            for(int x : arr){
                set.add(x);
            }
            int res = 0;
            for(int x: arr){
                if(set.contains(x+1))
                    res++;
            }
            return res;
        }
    }
    class Solution {
        public int countElements(int[] arr) {
            Arrays.sort(arr);
            int res = 0;
            int length = 1;
            for(int i = 1; i < arr.length; i++){
                if(arr[i-1] != arr[i]){
                    if(arr[i-1] + 1 == arr[i]){
                        res += length;
                    }
                    length = 0;
                }
                length++;
            }
            return res;
        }
    }

    Python3

    class Solution:
        def countElements(self, arr: List[int]) -> int:
            res = 0
            for num in arr:
                if num+1 in arr:
                    res += 1
            return res
    class Solution:
        def countElements(self, arr: List[int]) -> int:
            s = set()
            res = 0
            for x in arr:
                s.add(x)
            for x in arr:
                if x+1 in s:
                    res += 1
            return res
    class Solution:
        def countElements(self, arr: List[int]) -> int:
            arr.sort()
            res = 0
            length = 1
            for i in range(1, len(arr)):
                if arr[i-1] != arr[i]:
                    if arr[i-1] + 1 == arr[i]:
                        res += length
                    length = 0
                length += 1
            return res
  • 相关阅读:
    数论练习
    AC自动机*
    矩阵乘法*
    概率期望*
    组合数学练习*
    图论升级*
    【终端使用】"su"命令切换用户
    【终端使用】"which"命令可以查看执行命令所在的位置
    【终端使用】"usermod"命令 和 组(包括:主组、附加组)
    Ubuntu 18.04安装 MySQL 8.0+版本的数据库
  • 原文地址:https://www.cnblogs.com/yawenw/p/12659021.html
Copyright © 2011-2022 走看看