LeetCode Daily Question 4
Mar 8th 2022
3 月 8 日 每日一题
题目:217. Contains Duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
1 | eg: Input: nums = [1,2,3,1] |
思路
首先对 vector 进行 sort,之后遍历判断是否和上一个元素相同。时间复杂度 O(nlogn)空间复杂度取决于 sort。
有一个更简单的写法是直接用 set 判断 size。
1 | return set<int>(nums.begin(), nums.end()).size() < nums.size(); |
代码
1 | class Solution { |