Solution with two for loops
Example of an array, there is one odd occurring number, it is 9.Algorithm is following:
- Create dictionary (hash table) with keys of type Int and values of type Int. Key is number itself, value is counter of this number.
- First for loop. For each number in array
- If number already exist in dictionary then increment counter for this number by 1
- Else add this number to dictionary as key and assign value of 1 to this number
- Second for loop. For each key/value pair in dictionary
- If the value is odd (remainder of division by 2 is not 0) then return key (key is the number)
- By default return nil from function. So function will return type optional type Int?
Get result and check for errors
Optimised Solution
There are ways to modify and optimize first solution. When we iterate over elements in array we can check if number occur even number of times we can remove it from dictionary. So as result we will have in dictionary only numbers that occurred odd number of times. Here we have only one such number in array, so we return first key from dictionary.There is only one for loop over n elements is array. So time complexity will be O(n)
Get result and check for errors
Your article is one of its kind which explained every bit of Custom Build Website. looking for further valuable articles from you
ReplyDeleteYou wrote an amazing article. I am amazed, your efforts are showing in the article. I hope in future I will see more Articles from you.
ReplyDelete-Custom Website Design
Really great information you've offered; I've been seeking for stuff like this, so please continue to share it as much as you can. Best Custom Websites
ReplyDeleteThank you very much for sharing this informational blog.I could not find such kind of information in any other site.I'll come back for more fantastic material.
ReplyDeleteBest wishes, and good luck.
Custom Website