문제풀이 시도를 한 날: 2022년 10월 10일
문제를 푼 날: 2022년 10월 10일
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
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.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
1 <= nums.length <= 105109 <= nums[i] <= 109코드를 보면 알 수 있다. 더 설명할 여지가 없다.
c++ 의 map,unordered_map, unordered_set 의 insert 함수는 pair<iterator,bool> 를 반환하는데, 성공적으로 insert를 수행했다면, pair의 두 번째인 bool 타입의 값은 true가 되고, 아니라면 false가 된다. 위 자료구조들은 중복을 허용하지 않기 때문에 이미 값이 있었다면 false를 반환하는 것을 이용한 코드이다.
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> m;
for(int i: nums){
if(m.insert(i).second){
return true;
}
}
return false;
}
};