• 面试题3:数组中重复的数字


    代码啊代码:

    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        public static void main(String[] args) {
            Solution s = new Solution();
    
            int[] arr = new int[]{2, 3, 1, 0, 2, 5, 3};
            System.out.println(s.getDuplication(arr));
        }
    
        /**
         * 方法一:先排序,后遍历查找重复元素
         *
         * @param arr
         * @return
         */
        public int getDuplication1(int[] arr) {
            Arrays.sort(arr);
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] == arr[i + 1]) {
                    return arr[i];
                }
            }
            return -1;
        }
    
        /**
         * 方法二:借助哈希表来实现
         *
         * @param arr
         * @return
         */
        public int getDuplication(int[] arr) {
            Set<Integer> set = new HashSet<>(arr.length);
            for (int i = 0; i < arr.length; i++) {
                if (set.contains(arr[i])) {
                    return arr[i];
                }
                set.add(arr[i]);
            }
            return -1;
        }
    
        // 方法三:使用了巧方法,感觉没太大推广意义,这里就不写了
        // 方法四:利用了快排、递归、二分查找的思路,感觉没太大推广意义,这里就不写了
    }
    
  • 相关阅读:
    [Contest on 2020.4.2] 影帝杯狂欢赛
    [BZOJ 3821] 玄学
    CodeForces 432D Prefixes and Suffixes
    CodeForces 17E Palisection
    CodeForces 665E Beautiful Subarrays
    BZOJ 2989 数列
    changeeksdja
    Jmeter学习——1
    LoadRunner监控Linux与Windows方法(经典)
    LR检查点小结
  • 原文地址:https://www.cnblogs.com/optor/p/8630255.html
Copyright © 2020-2023  润新知