LeetCode编程练习 - 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.
给定一个正数数组,查找该数组是否包含任何重复项,如果数组中的任何值至少出现两次,函数返回true,若每个元素都是不同的,则返回false。
思路:
这与之前给一个排序数组删除重复元素Remove Duplicates from Sorted Array的思路相似。循环遍历每一个元素若找到一个则返回true,若没有则继续寻找,直到程序结束仍然没有就返回false。
这样写似乎没有错,但是使用的时间较长,需要重复与前面的元素比较,换一种写法,先对数组进行排序,只要判断前后值是否相同即可。