17、刪除排序連結串列中的重複元素
阿新 • • 發佈:2018-11-16
給定一個排序連結串列,刪除所有重複的元素,使得每個元素只出現一次。
示例 1:
輸入: 1->1->2
輸出: 1->2
示例 2:
輸入: 1->1->2->3->3
輸出: 1->2->3
我的未優化的程式碼
public static ListNode deleteDuplicates(ListNode head) { if(head == null){ return null; }else { ListNode listNode = head.next; ListNode s1 = new ListNode(head.val); ListNode s3 = s1; while (listNode != null) { int value = head.val; if(value == listNode.val){ System.out.println("相等"); listNode = listNode.next; }else { System.out.println("不相等"); ListNode s2 = new ListNode(listNode.val); s1.next = s2; s1 = s2; head = listNode; listNode = listNode.next; } } return s3; } }
經過優化過後的程式碼
不知道為什麼會提高這麼多,只是將空間複雜度降低了。。。
public static ListNode deleteDuplicates(ListNode head) { ListNode s4 = head; if(head == null){ return null; }else { ListNode listNode = head.next; while (listNode != null) { int value = head.val; if(value == listNode.val){ listNode = listNode.next; head.next = null; }else { head.next = listNode; head = listNode; listNode = listNode.next; } } return s4; } }
排名靠前的程式碼,不得不說這個程式碼簡單易懂,好吧,不是很容易懂,但是執行效率高
class Solution { public ListNode deleteDuplicates(ListNode head) { //遞迴到底 if (head == null) { return head; } head.next=deleteDuplicates(head.next); if ( head.next!=null && head.val== head.next.val) { return head.next; } return head; } }