
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Unique Integers in a Sorted List in Python
Suppose we have a list of sorted numbers called nums we have to find the number of unique elements in the list.
So, if the input is like nums = [3, 3, 3, 4, 5, 7, 7], then the output will be 4, as The unique numbers are [3, 4, 5, 7]
To solve this, we will follow these steps −
- s:= a new set
- cnt:= 0
- for each i in nums, do
- if i is not in s, then
- insert i into s
- cnt := cnt + 1
- if i is not in s, then
- return cnt
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): s=set() cnt=0 for i in nums: if i not in s: s.add(i) cnt += 1 return cnt ob = Solution() print(ob.solve([3, 3, 3, 4, 5, 7, 7]))
Input
[3, 3, 3, 4, 5, 7, 7]
Output
4
Advertisements