Java solution with sorting O(nlog(n)) time O(1) space


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

  • 0
    J

    As time complexity is more sensitive, we prefer a faster solution but o(n) space complexity which can be done using an hashset

    here is my c++ solution , of course it's simple , and everyone can come out with this idea

    class Solution {
        unordered_set<int> check;
    public:
        bool containsDuplicate(vector<int>& nums) {
            if(nums.size() <= 1)
                return false;
            for(int i = 0; i < nums.size(); i++){
                if(check.find(nums[i]) != check.end())
                    return true;
                check.insert(nums[i]);
            }
            return false;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.