题意:

image.png

解题思路:

  1. 思路:
  2. 1. 初始化 j = 0;
  3. 2. i1开始遍历,如果nums[i]和nums[j]不相等,则表明找到了新的元素,让nums[j++] = nums[i]
  4. 3. 最后返回j+1,因为j0开始;

PHP代码实现:

  1. class Solution {
  2. function removeDuplicates(&$nums) {
  3. return $this->removeDuplicates1($nums);
  4. $map = [];
  5. foreach ($nums as $k => $num) {
  6. if (in_array($num, $map)) unset($nums[$k]);
  7. array_push($map, $num);
  8. }
  9. }
  10. function removeDuplicates1(&$nums) {
  11. if (count($nums) == 0) return 0;
  12. $j = 0; $len = count($nums);
  13. for ($i = 1; $i < $len; $i++) {
  14. if ($nums[$i] != $nums[$j]) {
  15. $j++;
  16. $nums[$j] = $nums[$i];
  17. }
  18. }
  19. return $j + 1;
  20. }
  21. }

GO代码实现:

  1. func removeDuplicates(nums []int) int {
  2. if len(nums) == 0 { return 0 }
  3. j := 0
  4. if len(nums) == 1 { return 1 }
  5. for i := j + 1 ; i < len(nums); i++ {
  6. if nums[i] != nums[j] {
  7. j ++
  8. nums[j] = nums[i]
  9. }
  10. }
  11. return j + 1
  12. }