Given an array of integers, return a new array containing only the unique values.
The resulting array can be in any order.
Example:
Input: [2, 3, 1, 1, 4, 3, -2, 1] Output: [2, 3, 1, 4, -2]
Note:
For this lesson, your algorithm should run in O(n^2) time and use O(n) extra space.
(There are faster solutions which we will discuss in future lessons)
Hints:
Let's use an extra array
uniqueValues and add the unique values from nums there.
We can traverse the array nums from left to right. We should add the current element into uniqueValues only if that value has not been seen before. How can we check this?
The current element has never been seen before if it doesn't occur in
uniqueValues.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
