p82 array contains repeating elements (leetcode 217)

A: problem-solving ideas

First, a method easily conceivable that brute force method, the array of all numbers removed by two layers of the cycle, and then one by one comparison, the time complexity is O (n ^ 2) is too high, on the I do not write its code.

Method a: first sort the array, and the array is started from an index, compared with the previous one, until the traversed array. Time: (O (n * log (n))), Space: O (1)

Method 2: SET a collection, if it is found duplicate set of elements, which returns true.

Two: Complete code examples (C ++ version and the Java version)

Method one C ++:

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

        return false;
    }
};

Method One Java:

class Solution {
        public boolean containsDuplicate(int[] nums) 
        {
               if(nums==null || nums.length==0) return false;
               Arrays.sort(nums);
               for(int i=1;i<nums.length;i++)
               {
                   if(nums[i]==nums[i-1])
                       return true;
               }
               
               return false;
        }
    }

Method Two C ++:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums)
    {
        if (nums.size() == 0) return false;

        set<int> s;
        for (int i = 0; i < nums.size(); i++)
        {
            if (s.count(nums[i]) != 0) return true;
            s.insert(nums[i]);
        }

        return false;
    }
};

Method Two Java:

class Solution {
        public boolean containsDuplicate(int[] nums)
        {
            if(nums==null || nums.length==0) return false;
            Set<Integer> s=new HashSet<>();
            for(int num:nums)
            {
                if(s.contains(num)) return true;
                s.add(num);
            }

            return false;
        }
    }

 

Guess you like

Origin www.cnblogs.com/repinkply/p/12632880.html