leetcode (Single Number)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/86220038

Title:Single Number   136

Difficulty:Easy

原题leetcode地址:  https://leetcode.com/problems/single-number/

1.  见代码注释

时间复杂度:O(n),两次一层for循环,最长遍历为数组nums的长度。

空间复杂度:O(n),申请一个Map。

    /**
     * 采用HashMap
     * @param nums
     * @return
     */
    public static int singleNumber(int[] nums) {

        if (nums == null || nums.length <= 0) {
            return -1;
        }

        Map<Integer, Integer> map = new HashMap<>();

        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        for (int num : nums) {
            if (map.get(num) == 1) {
                return num;
            }
        }

        return -1;

    }

1.  见代码注释

时间复杂度:O(n),最长遍历为数组nums的长度。

空间复杂度:O(n),申请一个Set。

    /**
     * 采用Set + Math
     * @param nums
     * @return
     */
    public static int singleNumber2(int[] nums) {

        Set<Integer> set = new HashSet<>();
        int setTotal = 0;
        int numsTotal = 0;

        for (int num : nums) {
            numsTotal += num;
            set.add(num);
        }

        Iterator it = set.iterator();
        while (it.hasNext()) {
            setTotal += (Integer) it.next();
        }

        return 2 * setTotal - numsTotal;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/86220038