当前位置:网站首页>26. Delete the duplicate item C solution in the ordered array

26. Delete the duplicate item C solution in the ordered array

2022-07-04 19:20:00 charlsdm

To give you one Ascending order Array of nums , Would you please In situ Delete duplicate elements , Make each element Only once , Returns the new length of the deleted array . Elemental Relative order It should be maintained Agreement .

Because the length of an array cannot be changed in some languages , So you have to put the result in an array nums The first part of . More formally , If there is... After deleting duplicates k Elements , that nums Before k An element should hold the final result .

Insert the final result into nums Before k Return to... After a position k .

Don't use extra space , You must be there. In situ Modify input array And using O(1) Complete with extra space .

Criteria for judging questions :

The system will use the following code to test your solution :

int[] nums = […]; // Input array
int[] expectedNums = […]; // The expected answer with the correct length

int k = removeDuplicates(nums); // call

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass , Then your solution will be adopt .

Example 1:

Input :nums = [1,1,2]
Output :2, nums = [1,2,_]
explain : Function should return the new length 2 , And the original array nums The first two elements of are modified to 1, 2 . You don't need to think about the elements in the array that follow the new length .
Example 2:

Input :nums = [0,0,1,1,1,2,2,3,3,4]
Output :5, nums = [0,1,2,3,4]
explain : Function should return the new length 5 , And the original array nums The first five elements of are modified to 0, 1, 2, 3, 4 . You don't need to think about the elements in the array that follow the new length .

source : Power button (LeetCode)
link :https://leetcode.cn/problems/remove-duplicates-from-sorted-array
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

public class Solution
        {
    
            public int RemoveDuplicates(int[] nums)
            {
    
            int i = 0;
              
                    for(int j=1;j<nums.Length;j++)
                    {
    
                       
                        if(nums[i]!=nums[j])
                        {
    
                            nums[i + 1] = nums[j];
                            i = i + 1;
                           
                        }
                    }
                

                return i+1;

            }
            
            
    }
原网站

版权声明
本文为[charlsdm]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041739222613.html