Home > Software engineering >  remove the duplicates in-place such that each unique element appears only once
remove the duplicates in-place such that each unique element appears only once

Time:04-16

// Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. // Input: nums = [1,1,2] // Output: 2, nums = [1,2,_] // Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. // It does not matter what you leave beyond the returned k (hence they are underscores).

// Input: nums = [0,0,1,1,1,2,2,3,3,4] // Output: 5, nums = [0,1,2,3,4,,,,,_] // Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. // It does not matter what you leave beyond the returned k (hence they are underscores).

CodePudding user response:

int removeDuplicates(List<int> nums) {
  if(nums.length < 2) {
    return nums.length;
  }
  int p1 = 0, p2 = 1;
  while(p2 < nums.length) {
    if(nums[p1] < nums[p2]) {
      nums[  p1] = nums[p2];
    }
    p2  ;
  }
  return p1 1;
}

This is LC26. The solution is based on 2 pointer method where fist pointer points to latest unique number and second pointer is increased and checked if the new index value satisfied the condition if it's greater than first pointer index value.

CodePudding user response:

void main() {
  // Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
//   Input: nums = [1,1,2]
// Output: 2, nums = [1,2,_]
// Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
// It does not matter what you leave beyond the returned k (hence they are underscores).

// Input: nums = [0,0,1,1,1,2,2,3,3,4]
// Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
// Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
// It does not matter what you leave beyond the returned k (hence they are underscores).

  var array = [1, 1, 2];
  var array2 = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4];

  findExpectedArray(array2);
}

findExpectedArray(array) {
  var expectedArray = [];

  Set<int> setOfAray = array.toSet();

  for (var i = 0; i < array.length; i  ) {
    if (i < setOfAray.length) {
      expectedArray.add('${setOfAray.elementAt(i)}');
    } else {
      expectedArray.add('_');
    }
  }

  print(expectedArray);
}
  • Related