1. 程式人生 > 實用技巧 >判斷是否存在重複元素的各種程式碼整理

判斷是否存在重複元素的各種程式碼整理

給定一個整數陣列,判斷是否存在重複元素。

如果任意一值在陣列中出現至少兩次,函式返回true。如果陣列中每個元素都不相同,則返回false

最簡潔的程式碼: set函式去重

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums) != len(set(nums))

java 一行:

 public boolean containsDuplicate(int[] nums) {
            return Arrays.stream(nums).distinct().count() < nums.length;
    }

時空複雜度都很高

腦洞絕活類:

“隨機演算法,擲10萬次2個骰子,萬一發現有一次一樣的就有,10萬次都不一樣就當做不存在重複吧,特殊案例再處理一下。”

bool containsDuplicate(int* nums, int numsSize){
    int i;
    int a,b;
    srand(time(0));
    if(0 == numsSize||1 == numsSize ){
        return false;
    }
    for(i=0; i<100000; i++){
        a = rand()%numsSize;
        b 
= rand()%numsSize; if(a!=b && (nums[a] == nums[b])){ return true; } } return 9999 == nums[numsSize-1]; }

java自帶去重

class Solution {
public boolean containsDuplicate(int[] nums) {
        Set<Integer> res = new HashSet<Integer>();
        
for(int i:nums) res.add(i); return res.size()<nums.length; } }

java正常解法:

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                return true;
            }
        }
        return false;
    }
}