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); } }