leetcode之旅(8)-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.

Subscribe to see which companies asked this question

分析:

要求是找出整数数组的重复,如果重复是true;不重复返回false,先排序。判断相邻的元素是不是相同

思考:

可见排序的重要性,据说计算量的40%是排序

代码:

import java.util.Arrays;

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

你可能感兴趣的:(LeetCode,算法,面试,Contains-D)