TypechoJoeTheme

IT技术分享

统计

[LeetCode 217] Contains Duplicate [Java] [Beats : 99.39%]

2017-07-19
/
0 评论
/
672 阅读
/
正在检测是否收录...
07/19

1. Runtime Distribution

2. Submission Details

3. Description

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.

4. Example

input 2,3,1,0,2,5,3
output 2 or 3

5. Code

public boolean containsDuplicate(int[] nums) {

    int min=Integer.MAX_VALUE;
    int max=Integer.MIN_VALUE;
    for(int b: nums){
        if(b<min){
            min=b;
        }
        if(b>max){
            max=b;
        }
    }

    boolean record[] = new boolean[max-min+1];

    for(int num : nums){
        if(record[num-min]){
            return true;
        }else{
            record[num - min] = true;
        }
    }

    return false;
}

6.Test

public class LeetCode0217 {

    public boolean containsDuplicate(int[] nums) {

        int min=Integer.MAX_VALUE;
        int max=Integer.MIN_VALUE;
        for(int b: nums){
            if(b<min){
                min=b;
            }
            if(b>max){
                max=b;
            }
        }

        boolean record[] = new boolean[max-min+1];

        for(int num : nums){
            if(record[num-min]){
                return true;
            }else{
                record[num - min] = true;
            }
        }

        return false;
    }

    public static void main(String[] args) {
        LeetCode0217 leetcode = new LeetCode0217();
        int[] nums = {1,3,5,2,6,9,5};
        System.out.println(leetcode.containsDuplicate(nums));
    }
}
Array
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/585/(转载时请注明本文出处及文章链接)