217. Contains Duplicate

原题链接:https://leetcode.com/problems/contains-duplicate/description/
这是一道不错的题目:

import java.util.HashSet;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.containsDuplicate(new int[]{1, 2, 3, 5, 8, 7 ,2, 6}));
    }

    /**
     * 方法一:最黄最暴力的方法了,毫无疑问超时了
     *
     * 时间复杂度:O(n^2)
     * 空间复杂度:O(1)
     *
     * @param nums
     * @return
     */
    public boolean containsDuplicate1(int[] nums) {
        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;
    }

    /**
     * 方法二:在方法一的基础上进行优化,beats 7.56 %
     *
     * 时间复杂度:O(n)
     * 空间复杂度:O(n)
     *
     * @param nums
     * @return
     */
    public boolean containsDuplicate(int[] nums) {
        HashSet<Integer> set = new HashSet<>(nums.length);

        for (int i = 0; i < nums.length; i++) {
            if (set.contains(nums[i])) {
                return true;
            } else {
                set.add(nums[i]);
            }
        }
        return false;
    }

    // 然后,我就能想出上面两种方法了。最后,我们去看看官方答案吧:
    // 官方答案一:就是我的方法一
    // 官方答案二:先排序,然后再依次遍历一遍是否有重复值
    // 官方答案三:就是我的方法二了
    // 提交区有更多更牛逼的方法哦!
}
posted @ 2018-03-23 10:55  optor  阅读(96)  评论(0编辑  收藏  举报