Delete duplicate sorted array array - removing elements

26. Delete duplicates sort array

Given a sorted array, you need to remove the recurring elements in place, so that each element appears only once, after returning the new length of the array is removed.

Do not use extra space for an array, you must modify the input array in place and completed under the conditions of use O (1) extra space.

 

Example 1:

Given array nums = [1,1,2],

Function should return a new length of 2, and the first two elements of the original array is modified to nums 1, 2.

You do not need to consider beyond the elements of the new array length behind.
Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

New function should return the length 5 and the first five elements of the original array nums is modified to 0, 1, 2, 3, 4.

You do not need to consider beyond the elements of the new array length behind.

 1 public class T26 {
 2     public int removeDuplicates(int[] nums) {
 3         int slow = 0, fast = 1;
 4         int count = 1;
 5         while (fast < nums.length) {
 6             if (nums[slow] == nums[fast]) {
 7                 fast++;
 8             } else {
 9                 nums[slow + 1] = nums[fast];
10                 slow++;
11                 count++;
12             }
13         }
14         return count;
15     }
16 }

27. remove elements

Nums give you an array and a value val, you need to remove all values ​​equal to place elements of val, and returns the new length of the array after removal.

Do not use extra space for an array, you must use only (1) extra space and place O modify the input array.

Order of the elements may be changed. You do not need to consider beyond the elements of the new array length behind.

 

Example 1:

Given nums = [3,2,2,3], val = 3,

Function should return a new length of 2, and the first two elements nums are 2.

You do not need to consider beyond the elements of the new array length behind.
Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

New function should return the length 5 and the first five elements nums is 0, 1, 3, 0, 4.

Note that these five elements can be in any order.

You do not need to consider beyond the elements of the new array length behind.

 1 public class T27 {
 2     public int removeElement(int[] nums, int val) {
 3         int slow = 0, fast = 0;
 4         int count = 0;
 5         while (fast < nums.length) {
 6             if (nums[fast] == val) {
 7                 fast++;
 8                 count++;
 9             } else {
10                 nums[slow++] = nums[fast++];
11             }
12         }
13         return nums.length - count;
14     }
15 }

 

Guess you like

Origin www.cnblogs.com/zzytxl/p/12508266.html