LeetCode【217. 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.

思路1.

对每一个数字都与其后序的数字进行比较,如果相同则返回true,如果不同,则指导遍历完最后一个数字返回false,时间复杂度为(n-1)+(n-2)+....2+1,所以是O(n2),代码就不写了,这方法不好。

思路2.

先排序,然后在遍历vector,如果有相邻的值相同,则返回true,负责将pivot设置为当前的值。总的时间复杂度为排序O(nlogn)+遍历O(n)

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
         bool flag = false;
         int len = nums.size();
         if(len > 1)
         {
            sort(nums.begin(),nums.end());
            int MarkNum = nums[0];
            for(int i = 1; i<= len; i++)
            {
                if(nums[i] == MarkNum)
                    flag = true;
                else
                    MarkNum=nums[i];
            }
         }
         else
          flag = false;
    return flag;
    }
};

  

思路3,利用额外空间,unordered_map,如果元素不存在,计数器的值加1,如果存在,则返回true

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int,int> cmpMap;
        for( int i = 0; i < nums.size(); i++ ){
            if( cmpMap.find(nums[i]) == cmpMap.end() ){
                cmpMap[nums[i]]++;
            }
            else{
                return true;
            }
        }
        return false;
    }
};

思路3我本来以为时间复杂度应该在O(n)但提交以后,速度还没思路2的快,不知道是什么原因。

时间: 2024-10-06 01:43:07

LeetCode【217. Contains Duplicate】的相关文章

leetcode 【 Pascal&#39;s Triangle 】python 实现

题目: Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 代码:oj测试通过 Runtime: 46 ms 1 class Solution: 2 # @return a list of lists of integers 3 def generat

leetcode 【 Trapping Rain Water 】python 实现

题目: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. The above elevation map is represented

leetcode 【 Merge Sorted Array 】python 实现

题目: Given two sorted integer arrays A and B, merge B into A as one sorted array. Note:You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B ar

leetcode 【 Find Peak Element 】python 实现

题目: A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks i

leetcode 【 Set Matrix Zeroes 】python 实现

题目: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. click to show follow up. Follow up: Did you use extra space?A straight forward solution using O(mn) space is probably a bad idea.A simple improvement us

leetcode 【 Insertion Sort List 】 python 实现

题目: Sort a linked list using insertion sort. 代码:oj测试通过 Runtime: 860 ms 1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 # @param head, a ListNode 9 # @re

[LeetCode] NO.217 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. [题目解析] 直接想到的方法是用hash,遍历记录数组中每个元素出现

leetcode 【 Minimum Path Sum 】python 实现

题目: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 代码:oj测试通过 Runtime: 102 ms 1 c

LeetCode 【31. Next Permutation】

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replaceme