中级农民
积分 298
大米 颗
鳄梨 个
水井 尺
蓝莓 颗
萝卜 根
小米 粒
学分 个
注册时间 2012-12-2
最后登录 1970-1-1
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
麻烦帮我看一下这个题,会尽力为大家加米,谢谢。
-----------------------题目描述-------------------------------------------------
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
我的疑问是:
我用下面代码的逻辑在python3里写了一遍,运行出来的结果是[1,2,3,5];我认为在第20行slow.next = fast.next;, slow已经指向了3,所以3被保留在了结果中。感觉这个逻辑是不对的,为什么Java的结果通过了呢?
-------------------accepted Java代码----------------------------------
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
//use two pointers, slow - track the node before the dup nodes,
// fast - to find the last node of dups.
ListNode dummy = new ListNode(0), fast = head, slow = dummy;
slow.next = fast;
while(fast != null) {
while (fast.next != null && fast.val == fast.next.val) {
fast = fast.next; //while loop to find the last node of the dups.
}
if (slow.next != fast) { //duplicates detected.
slow.next = fast.next; //remove the dups.
fast = slow.next; //reposition the fast pointer.
} else { //no dup, move down both pointer.
slow = slow.next;
fast = fast.next;
}
}
return dummy.next;
}
} 复制代码
------wrong answer python 3 code--------------
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
dummy = ListNode(0);
slow = dummy;
fast = head;
slow.next = fast;
while (fast):
while (fast.next and fast.val == fast.next.val) :
fast = fast.next;
if (slow.next.val != fast.val):
slow.next = fast.next;
fast = slow.next;
else:
slow = slow.next;
fast = fast.next;
return dummy.next; 复制代码
上一篇:
刷题分享帖之 291 下一篇:
各位chaser,如何找到好的实习....