LeetCode:Contains Duplicate - 判斷數組內是否有重複元素

一、題目名稱java

Contains Duplicate(判斷數組內是否有重複元素)數組

二、題目地址app

https://leetcode.com/problems/contains-duplicate/code

三、題目內容排序

英文: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.element

中文:給出一個整數數組,判斷該數組內是否有兩個元素值是相同的,是則返回true,不然返回falseleetcode

四、解題方法1開發

先將傳入的數組進行排序,排序後查看相鄰元素,若是存在相鄰元素相同的狀況,則說明原數組內有至少兩個元素相同。get

Java代碼以下:hash

import java.util.Arrays;

/**
 * @功能說明:LeetCode 217 - Contains Duplicate
 * @開發人員:Tsybius2014
 * @開發時間:2015年10月12日
 */
public class Solution {
    
    /**
     * 查看數組內是否有重複元素
     * @param nums
     * @return
     */
    public boolean containsDuplicate(int[] nums) {
        
        if (nums.length <= 1) {
            return false;
        }
        
        Arrays.sort(nums);
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) {
                return true;
            }
        }
        
        return false;
    }
}

五、解題方法2

遍歷數組,將數組內的值逐個放入到一個HashMap中,若是遍歷到某元素是發現該元素值已經在HashMap中存在,則說明原數組中存在重複的元素。

Java代碼以下:

import java.util.HashMap;

/**
 * @功能說明:LeetCode 217 - Contains Duplicate
 * @開發人員:Tsybius2014
 * @開發時間:2015年10月12日
 */
public class Solution {
    
    /**
     * 查看數組內是否有重複元素
     * @param nums
     * @return
     */
    public boolean containsDuplicate(int[] nums) {
        
        if (nums.length <= 1) {
            return false;
        }

        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.containsKey(nums[i])) {
                return true;
            } else {
                hashMap.put(nums[i], i);
            }
        }
        
        return false;
    }
}

END

相關文章
相關標籤/搜索