# 算法练习(2)-删除有序数组/单链表中的重复项

删除有序数组(或有序单链表)中的重复项。

输入[1,1,2,2,3] 输出[1,2,3]

输入a->b->b->c->c 输入a->b->c

    /**
* 有序数组删除重复项
* @param nums
* @return 去重后的元素个数
*/
public int removeDuplicates(int[] nums) {
if (nums == null) {
return 0;
}
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[i] != nums[j]) {
i++;
if (j - i > 0) {
nums[i] = nums[j];
}
}
}
return i + 1;
}


注：j即为快指针，i为慢指针，如果每个元素都不同的情况下，比如[1,2,3]，为了减少无意义的移动赋值，所以加了if(j-i)>0的判断。

    private void removeDuplicate(Node dummy) {
//辅助行，输出整个链表
printNode(dummy);
Node slow = dummy.next;
Node fast = slow.next;
while (true) {
if (fast.value != slow.value) {
slow.next = fast;
slow = slow.next;
}
fast = fast.next;
if (fast == null) {
slow.next = null;
break;
}
}
//辅助行，输出整个链表
printNode(dummy);
}


    private int removeDuplicate2(char[] src) {
if (src == null || src.length <= 1) {
return 0;
}
//辅助行,打印日志
System.out.println(new String(src));
int i = 0;
for (int j = 1; j < src.length; j++) {
boolean found = false;
for (int k = 0; k <= i; k++) {
if (src[k] == src[j]) {
found = true;
break;
}
}
if (!found) {
i++;
src[i] = src[j];
}
}
//辅助行，输出最终结果
System.out.println(new String(Arrays.copyOf(src, i + 1)));
return i + 1;
}


    private void removeDuplicate3(Node dummy) {
//辅助行，输出整个链表
printNode(dummy);
Node slow = dummy.next;
Node fast = slow.next;
while (true) {
Node temp = dummy.next;
boolean found = false;
while (temp != null) {
if (temp.value == fast.value) {
found = true;
break;
}
if (temp.next == slow.next) {
break;
}
temp = temp.next;
}
if (!found) {
slow.next = fast;
slow = slow.next;
}
fast = fast.next;
if (fast == null) {
slow.next = null;
break;
}
}
//辅助行，输出整个链表
printNode(dummy);
}


    void removeDuplicate4(Node dummy) {
//辅助行，输出整个链表
printNode(dummy);
Node curr = dummy.next;
Set<String> set = new HashSet<>();
while (curr != null && curr.next != null) {
if (set.contains(curr.next.value)) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
//辅助行，输出整个链表
printNode(dummy);
}


posted @ 2020-06-26 10:42  菩提树下的杨过  阅读(290)  评论(0编辑  收藏