LeetCode:Remove Duplicates from Sorted Array

来源:互联网 发布:全球指数交易软件 编辑:程序博客网 时间:2024/05/14 20:36

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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

稍难点的基本编程题

我改善了算法(一上来居然没有想到,编程能力还是有待提高):

public int removeDuplicates(int[] A) { if (A.length == 0) { return 0; } int current = 1; int index = 1; int pre = A[0]; while (index < A.length) { if (!(A[index] == pre)) { A[current++] = A[index]; } pre = A[index]; index++; } return current; }


刚才的代码:

package leetcode;import java.io.IOException;import java.io.InputStreamReader;import java.io.StreamTokenizer;public class RemoveDuplicatesfromSortedArray {static {        System.setIn(JumpGameII.class.getResourceAsStream("/data/leetcode/RemoveDuplicatesfromSortedArray.txt"));    }    private static StreamTokenizer stdin = new StreamTokenizer(new InputStreamReader(System.in));    private static int readInt() throws IOException {        stdin.nextToken();        return (int) stdin.nval;    }/** * @param args */public static void main(String[] args) throws IOException {RemoveDuplicatesfromSortedArray s = new RemoveDuplicatesfromSortedArray();    int[] m = new int[2];    for (int i = 0; i < m.length; i++) {    m[i] = readInt();    }    long start = System.currentTimeMillis();System.out.println(s.removeDuplicates(m));for (int i : m) {System.out.println(i);}System.out.println("time:" + (System.currentTimeMillis() - start));} public int removeDuplicates(int[] A) {if (A.length == 0) {return 0;}int len = A.length;int index = A.length - 1;while (index >= 0) {int minIndex = index;while (minIndex >= 0 && A[minIndex] == A[index]) {minIndex--;}minIndex++;if (minIndex != index) {int interval = index - minIndex;len -= interval;for (int i = minIndex; i < len; i++) {A[i] = A[i + interval];}index = minIndex - 1;} else {index--;}}return len;}}