- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to remove duplicates from the sorted array and return the length using C#?
The array is already sorted, we can keep two pointers ii and jj, where ii is the slow-runner while jj is the fast-runner. As long as nums[i] = nums[j]nums[i]=nums[j], we increment jj to skip the duplicate.
When we encounter nums[j] != nums[i] the duplicate run has ended so we must copy its value to nums[i + 1]nums[i+1]. ii is then incremented and we repeat the same process again until jj reaches the end of array.
Time complexity − O(N)
Example
using System; namespace ConsoleApplication{ public class Arrays{ public int RemoveDuplicatesFromSortedArrayAndReturnLength(int[] arr){ int index = 1; for (int i = 0; i < arr.Length - 1; i++){ if (arr[i] != arr[i + 1]){ arr[index] = arr[i + 1]; index++; } else{ continue; } } return index; } } class Program{ static void Main(string[] args){ Arrays a = new Arrays(); int[] arr = { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 }; int res = a.RemoveDuplicatesFromSortedArrayAndReturnLength(arr); Console.WriteLine(res); Console.ReadLine(); } } }
Output
5
Advertisements