在linkedlist中找到重复的数量 - 边缘案例测试失败
我被要求编码以下问题:
问题描述:
给定链接列表,在中找到重复元素的数量 列表。
输入格式:
第一行包含一个整数
n
- 节点的数量。第二行包含
n
整数-Node values 。输出格式:
打印重复的总数。
约束:
n< = 10^5
node< =
的值10^6
示例输入:
9
1 2 3 4 4 5 6 6 6
< < em>示例输出:
3
说明:
在给定的测试用例中,我们有3
重复项,即一个4
和两个6
。
我的代码:
import crio.ds.List.*;
/*public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; next = null; }
}*/
public class Solution {
public int countDuplicatesInALinkedList(ListNode head){
int counter = 0;
while(head.next != null){
ListNode ptr = head.next;
while(ptr != null){
if(head.val == ptr.val){
counter++;
break;
}
ptr = ptr.next;
}
head = head.next;
}
return counter;
}
}
我想了解为什么我的代码失败了边缘情况。
I was asked to code for the following problem:
Problem Description:
Given a linked list, find the number of duplicate elements in the
list.Input Format:
First line contains an integer
N
- The number of nodes.Second line contains
N
integers - Node values.Output Format:
Print the total number of duplicates.
Constraints:
N <= 10^5
Value of node <=
10^6
Sample Input:
9
1 2 3 4 4 5 6 6 6
Sample Output:
3
Explanation:
In the given test case we have 3
duplicates i.e. one 4
and two 6
.
My code:
import crio.ds.List.*;
/*public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; next = null; }
}*/
public class Solution {
public int countDuplicatesInALinkedList(ListNode head){
int counter = 0;
while(head.next != null){
ListNode ptr = head.next;
while(ptr != null){
if(head.val == ptr.val){
counter++;
break;
}
ptr = ptr.next;
}
head = head.next;
}
return counter;
}
}
I want to understand why my code is failing the edge case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当 head-node 是
null
您的代码将产生nullpoInterException
当它输入ofter时,
-loop( 在评估条件head.next!= null
时,如果头为null
)。另外,您的解决方案效率低下。您正在检查列表中所有其他值的每个值,并需要一个二次时间 o(n^2)运行。
可以在列表中的单个通过和更少的代码中,可以在衬里时间 o(n)中解决此问题。
为此,您可以使用
Hashset
,该将存储每个先前遇到的值。如果 set 拒绝的提供的值,即see.add()
返回false
,则意味着此值是重复的。sideNote:,不认为将接收到方法参数的对象修改为一个好习惯。
When the head-node is
null
your code will produce aNullPointerException
when it enters the outerwhile
-loop (while evaluating the conditionhead.next != null
, which will fail if head isnull
).Also, your solution is inefficient. You're checking every value against all others values in the list and takes a quadratic time O(n^2) to run.
This problem can be solved in a liner time O(n), in a single pass through the list and fewer code.
For that, you can utilize a
HashSet
which will store every previously encountered value. If an offered value rejected by the set, i.e.seen.add()
returnsfalse
, that means this value is a duplicate.Sidenote: it's not considered to be a good practice to modify objects received as method parameters.