Last active
October 20, 2019 21:04
-
-
Save marta-krzyk-dev/155c9c0ab54edea1dcdf89fd1cb5abc9 to your computer and use it in GitHub Desktop.
Find duplicates in int array with O(n) using Hashtable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://leetcode.com/problems/find-all-duplicates-in-an-array/ | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class Solution { | |
public IList<int> FindDuplicates(int[] nums) { | |
if (nums is null) | |
return null; | |
List<int> duplicates = new List<int>(); | |
if (nums.Length < 2) | |
return duplicates; | |
Hashtable hashTable = new Hashtable(); | |
hashTable.Add(nums[0], nums[0]); | |
for(int x = 1, elem = nums[1]; x < nums.Length; ++x) | |
{ | |
elem = nums[x]; | |
if (hashTable.ContainsKey(elem)) | |
duplicates.Add(elem); | |
else | |
hashTable.Add(elem, elem); | |
} | |
return duplicates; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
www.leetcode.com/problems/find-all-duplicates-in-an-array/
O(n) complexity