LeetCode 217. Contains Duplicate(Java)
2016-12-07 23:25
295 查看
原题:
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
题意:
给定一个整数数组,如果数组中存在至少两个重复元素(复制品)则返回true,否则返回false,即数组中的元素都是唯一的。
思路:
1.利用Set集合中元素都是唯一的特点进行存储;
2.当set.add(num[i])返回false时则代表该数在set中已经存在,没有继续添加,此时方法返回true,即存在复制品;
3.如果遍历完数组没有出现复制品,则返回false。
代码:
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
题意:
给定一个整数数组,如果数组中存在至少两个重复元素(复制品)则返回true,否则返回false,即数组中的元素都是唯一的。
思路:
1.利用Set集合中元素都是唯一的特点进行存储;
2.当set.add(num[i])返回false时则代表该数在set中已经存在,没有继续添加,此时方法返回true,即存在复制品;
3.如果遍历完数组没有出现复制品,则返回false。
代码:
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int num:nums){ if(!set.add(num)){ return true; } } return false; } }
相关文章推荐
- LeetCode – Remove Duplicates from Sorted Array (Java)
- Java for LeetCode 087 Scramble String
- 【leetcode】81. Search in Rotated Sorted Array II【java】
- LeetCode-598. Range Addition II (Java)
- Copy List with Random Pointer leetcode java
- LeetCode【8】. String to Integer (atoi) --java实现
- LeetCode 637 : Average of Levels in Binary Tree(java)
- [LeetCode][Java] Binary Tree Inorder Traversal
- [LeetCode][Java] Binary Tree Preorder Traversal
- leetcode 373 Find K Pairs with Smallest Sums java
- leetcode解题之23.Merge k Sorted Lists Java版本(合并k个有序的链表)
- 【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
- LeetCode 85 (Maximal-Rectangle)java
- Java for LeetCode 222 Count Complete Tree Nodes
- 【leetcode】Reverse Linked List II (Java)
- LeetCode|Same Tree-java
- LeetCode|Reverse Words in a String-java
- leetcode 002 Add Two Numbers(java)
- [leetcode-41]First Missing Positive(java)
- [LeetCode] 004. Median of Two Sorted Arrays (Hard) (C++/Java/Python)