本文主要是介绍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之旅(8)-Contains Duplicate的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!