【LeetCode-面試演算法經典-Java實現】【217-Contains Duplicate(包含重複元素)】,leetcode--java
【217-Contains Duplicate(包含重複元素)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】代碼下載【https://github.com/Wang-Jun-Chao】原題
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。
解題思路
用set資料結構
代碼實現
演算法實作類別
import java.util.HashSet;import java.util.Set;public class Solution { public boolean containsDuplicate(int[] nums) { // 元素個數大於1才進行下面的操作 if (nums != null && nums.length > 1) { //建立一個hashSet Set<Integer> set = new HashSet<>(nums.length); for(int i : nums) { // 如果元素已經存在就返回true if (set.contains(i)) { return true; } // 沒有就添加到元素集合中 else { set.add(i); } } } return false; }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/48046275】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。