LeetCode_26---Remove Duplicates from Sorted Array

来源:互联网 发布:c 数组 编辑:程序博客网 时间:2024/05/29 23:24

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

fan

Code:

package mengdexinTest;import java.util.Arrays;//436msApublic class LeetCode26 {public static int removeDuplicates(int[] nums) {int len = nums.length;int result = 0;int start = 0;while (start < len) {nums[result] = nums[start];while (start + 1 < len) {if (nums[start] == nums[start + 1]) {start++;} else {break;}}start++;result++;}return result;}public static void main(String[] args) {int[] a = { 1, 2, 2, 2, 3, 3, 6, 9 };int[] b = { 1 };int[] c = { 2, 2, 2 };int[] d = {};System.out.println("第二种:" + removeDuplicates(a));System.out.println("第二种:" + Arrays.toString(a));}}


0 0
原创粉丝点击