美文网首页
数组中重复的数字

数组中重复的数字

作者: 不会游泳的金鱼_ | 来源:发表于2019-08-12 16:25 被阅读0次

范围已知的时候可以直接用数组搞定,否则用哈希。

数组法:

    /**
     * 
     * @title: duplicate 
     * @description: 查找数组中重复的数字,数字范围0~n
     */
    public static int duplicate(int[] arr, int n) {
        if(arr == null || arr.length<= 0) {
            return 0;
        }
        int[] temp = new int[n+1];
        for(int i = 0; i < arr.length; i++) {
            
            if(temp[arr[i]] != 0) {
                return arr[i];
            }else {
                temp[arr[i]] = 1;
            }
        }
        return 0;
    }

哈希法:

    /**
     * 
     * @title: duplicate 
     * @description: 查找数组中重复的数字
     */
    public static int duplicate(int[] arr) {
        if(arr == null || arr.length<= 0) {
            return -1;
        }
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < arr.length; i++) {
            if(map.containsKey(arr[i])) {
                return arr[i];
            }else {
                map.put(arr[i], 1);
            }
                
        }
        return -1;
    }

字符串中重复的字母:

    /**
     * 
     * @title: duplicate 
     * @description: 查找字符串中的重复字符
     */
    public static char duplicate(String str) {
        char[] arr = str.toCharArray();
        int[] temp = new int[128];
        for(int i = 0 ;i < str.length(); i++) {
            if(temp[arr[i]] != 0) {
                return arr[i];
            }else {
                temp[arr[i]] = 1;
            }
        }
        return 0;
    }

相关文章

  • 剑指offer题集

    [3] 数组中重复的数字 题目一:找出数组中重复的数字 Description 在一个长度为n的数组里的所有数字都...

  • LeetCode 每日一题 [38] 数组中重复的数字

    LeetCode 数组中重复的数字 [简单] 找出数组中重复的数字。在一个长度为 n 的数组 nums 里的所有数...

  • 剑指offer4J【C2 P3】找出数组中重复数字

    题目 找出数组中重复的数字数组中数字都在0~n之间,其中有些数字是重复的,但不知道谁重复,可能有1到多个重复的数字...

  • 面试题03. 数组中重复的数字

    数组中重复的数字 题目描述 找出数组中重复的数字。 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-...

  • 数组中重复的数字

    题目一:找出数组中重复的数字 在一个长度为 n 的数组里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复...

  • 剑指offer学习笔记:8.1 数组

    面试题51:数组中重复的数字在一个长度为n的数组中,所有数字都在0到n-1的范围内。数组中的某些数字是重复的,但是...

  • 数组中重复的数字

    题目描述 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重...

  • 数组中重复的数字

    数组中重复的数字 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个...

  • 数组中重复的数字

    题目描述 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重...

  • 数组中重复的数字

    在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不...

网友评论

      本文标题:数组中重复的数字

      本文链接:https://www.haomeiwen.com/subject/jciujctx.html