Saturday, September 26, 2009

fix duplicates in sorted array

12233344445 -> 12345

//using 3 pointers
fixDuplicatesInSortedArray(int[] a):
    start = 0
    destination = 0
    end = 0
    while (end < a.Length):
        while (end < a.Length && a[end] == a[start]):
            end++
        a[destination++] = a[start]
        start = end
    
    while (destination < a.Length):
        a[destination++] = null
    return

//using 2 pointers
fixDuplicatesInSortedArray(int[] a):
    target = 0
    for i = 0, i < a.length(), i++:
        if a[i] != a[target]:
            target++
            a[target] = a[i]
    target++
    while target < a.length():
        a[target] = null
        target++


[Hat tip to MG]

No comments:

Post a Comment