https://leetcode.cn/problems/remove-duplicates-from-sorted-array/description/?envType=study-plan-v2&envId=top-interview-150
package leetcode150 import "testing" func TestRemoveDuplicates(t *testing.T) { nums := []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4} res := removeDuplicates2(nums) println(res) for i := range nums { if i >= res { break } print(nums[i]) print(" ") } } func removeDuplicates(nums []int) int { numMap := make(map[int]int) i := 0 for _, num := range nums { if numMap[num] == 0 { nums[i] = num i++ } numMap[num]++ } return i } func removeDuplicates2(nums []int) int { i := 0 j := 0 for j < len(nums) { if nums[i] == nums[j] { j++ } else { i++ nums[i] = nums[j] } } return i + 1 }
java
package leetcode150; import org.junit.Test; public class a3_26_RemoveDuplicates { @Test public void test(){ int[] nums = new int[]{1,1,2}; int res = RemoveDuplicates(nums); System.out.println(res); for (int i = 0; i < nums.length; i++) { System.out.print(nums[i] + " "); } } public int RemoveDuplicates(int[] nums) { int i = 0, j = 0; while (i < nums.length && j < nums.length) { if (nums[i] == nums[j]) { j++; } else { nums[++i] = nums[j]; } } return i + 1; } }