clueless coding // TODO: be smarter

LeetCode 217. Contains Duplicate: C++ Solution



Problem Statement


Given an array of integers, design an algorithm to find if it contains duplicates.

Return true if any value appears two or more times in the array.

Return false if every element is distinct.

Function Signature (C++):
  bool containsDuplicate(vector<int>& nums)

Inputs:
  nums = [1, 2, 3, 4, 1]

Outputs:
true

Inputs:
  nums = [1, 2, 3, 4]

Outputs:
false



TL;DR Code Solution


bool containsDuplicate(vector<int>& nums) {

    unordered_map<int, bool> map;

    for (int i = 0; i < nums.size(); i++) {

        if (map.count(nums[i])) {
            return true;
        }
        else {
            map[nums[i]] = true;
        }

    }

    return false;

}