方法一:排序

注意:不是最优的

方法二:哈希表

注意:时间复杂度可以降到O(N)

也可以使用set

  1. class Solution {
  2. public:
  3. bool containsDuplicate(vector<int>& nums) {
  4. //使用map进行判断
  5. map<int, bool> hmap;
  6. for(int i = 0; i < nums.size(); i++)
  7. {
  8. //如果已经存在于map中,直接返回true
  9. if (hmap[nums[i]])
  10. {
  11. return true;
  12. }
  13. hmap[nums[i]] = true;
  14. }
  15. return false;
  16. }
  17. };
  1. func containsDuplicate(nums []int) bool {
  2. //直接使用hmap进行计数
  3. hmap := map[int]int{}
  4. for _, v := range nums {
  5. if _, ok := hmap[v]; ok {
  6. return true
  7. } else {
  8. hmap[v] = 1
  9. }
  10. }
  11. return false
  12. }