zoukankan      html  css  js  c++  java
  • leetcode-217-存在重复元素

    问题:

    package com.example.demo;
    
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    
    public class Test217 {
    
        /**
         * 方法一:暴力解法,在leetcode上会超时
         */
        public boolean containsDuplicate(int[] nums) {
            if (nums == null || nums.length == 0) {
                return false;
            }
    
            for (int i = 0; i < nums.length; i++) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[i] == nums[j]) {
                        return true;
                    }
                }
            }
            return false;
        }
    
        /**
         * 方法二:借助排序,在比较相邻值
         */
        public boolean containsDuplicate1(int[] nums) {
            Arrays.sort(nums);
            int cur = 0;
            while (cur < nums.length - 1) {
                if (nums[cur] == nums[++cur]) {
                    return true;
                }
            }
            return false;
        }
    
        /**
         * 方法三:借助hash表
         */
        public boolean containsDuplicate2(int[] nums) {
            Set<Integer> set = new HashSet<>();
            for (Integer num : nums) {
                if (set.contains(num)) {
                    return true;
                }
                set.add(num);
            }
            return false;
        }
    
        public static void main(String[] args) {
            Test217 t = new Test217();
            int[] arr = {1, 2, 3, 4, 5, 7};
            boolean b = t.containsDuplicate2(arr);
            System.out.println(b);
        }
    }
  • 相关阅读:
    Elixir 学习资源
    elixir 模块
    elixir 表单 map
    elixir 关键字列表
    elixir case cond if
    elixir 模式匹配
    elixir 基础数据结构
    5、OpenCV Python ROI和泛洪填充
    6、OpenCV Python 图像模糊
    4、OpenCV Python 像素运算
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11268977.html
Copyright © 2011-2022 走看看