LeetCode # Array # Easy # 217. Contains Duplicate
生活随笔
收集整理的這篇文章主要介紹了
LeetCode # Array # Easy # 217. Contains Duplicate
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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。
思路:首先想到用一個hashmap存元素,遍歷數組,如果在map中能查到則返回true,否則將該元素存入map。
這種方法空間復雜度較低,時間復雜度為0(N)
1 import java.util.HashMap; 2 3 class Solution { 4 public boolean containsDuplicate(int[] nums) { 5 HashMap<Integer, Integer> map = new HashMap<>(); 6 int n = nums.length; 7 boolean tag = false; 8 for(int i =0; i< n; i++){ 9 if(map.containsKey(nums[i])){ 10 tag = true; 11 }else{ 12 map.put(nums[i], 1); 13 } 14 } 15 return tag; 16 } 17 }然后,最佳方法的思路是:先找到最大元素和最小元素,然后設置一個bool類型數組。
如果一個數num-min 的bool變量為空,則是第一次出現,將其bool變量設置成true。若不為空,則說明其為重復元素,返回true。
1 class Solution { 2 public boolean containsDuplicate(int[] nums) { 3 if(nums == null || nums.length == 1) return false; 4 int max = Integer.MIN_VALUE; 5 int min = Integer.MAX_VALUE; 6 for(int num : nums){ 7 if(num > max) 8 max = num; 9 if(num < min) 10 min = num; 11 } 12 boolean[] bool = new boolean[max - min + 1]; 13 for(int num : nums){ 14 if(bool[num - min])//如果這個bool值=-true,則返回true 15 return true; 16 else 17 bool[num - min] = true; 18 } 19 return false; 20 } 21 }?
轉載于:https://www.cnblogs.com/DongPingAn/p/8994655.html
總結
以上是生活随笔為你收集整理的LeetCode # Array # Easy # 217. Contains Duplicate的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 移动硬盘磁盘结构损坏且无法读取要怎样办啊
- 下一篇: 第04次作业-树