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
  • 相关阅读:
    Django入门
    Python从入门到放弃
    Python中的元类(metaclass)
    蓝鲸gse启动失败
    VS2019添加微软ReportViewer
    DevExpress WinForms各版本与 .NET、Visual Studio 的版本兼容性
    SQL语句查询每个分组的前N条记录的实现方法
    如何查看Windows安装版本号
    学习webpack
    Python3.x将代码打包成exe程序并添加图标
  • 原文地址:https://www.cnblogs.com/yawenw/p/12659021.html
Copyright © 2011-2022 走看看