Contains Duplicate

来源:互联网 发布:java基础知识点汇总 编辑:程序博客网 时间:2024/05/17 01:41

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.

java代码:

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

219. Contains Duplicate II
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

java代码:

public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {        int n = nums.length;        // prevent time limit exceeded        int[] a = new int[n];        for(int i=0;i<n;i++)            a[i]=nums[i];        Arrays.sort(a);        int flag1 = 0;        for(int i=1;i<n;i++){            if(a[i]==a[i-1]){                flag1 = 1;            }        }        if(flag1==0){            return false;        }        for(int i=0;i<n;i++){            int flag = n < i+k+1 ? n : i+k+1;            for(int j=i+1;j<flag;j++){                if(nums[i]==nums[j] && j-i<=k)                    return true;            }        }        return false;    }}
0 0
原创粉丝点击