zoukankan      html  css  js  c++  java
  • LeetCode 83. Remove Duplicates from Sorted List (从有序链表中去除重复项)

    Given a sorted linked list, delete all duplicates such that each element appear only once.

    For example,
    Given 1->1->2, return 1->2.
    Given 1->1->2->3->3, return 1->2->3.


    题目标签:Linked List

      题目给了我们一个 list,让我们去除中间的重复项。

      设一个 cursor = head,遍历list,每一次比较 cursor 和 cursor.next,如果一样,发现重复项,把cursor link 到 next next node 即可;如果不一样,移动cursor到下一个点。

    Java Solution:

    Runtime beats 18.22% 

    完成日期:06/09/2017

    关键词:singly-linked list

    关键点:比较cursor 和 cursor.next,一样就把cursor link 到 next next node。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution 
    10 {
    11     public ListNode deleteDuplicates(ListNode head) 
    12     {
    13         ListNode cursor = head;
    14        
    15         while(cursor != null)
    16         {
    17             if(cursor.next != null && cursor.val == cursor.next.val) // if find a duplicate one
    18             {
    19                 ListNode duplicate = cursor.next;
    20                 
    21                 cursor.next = duplicate.next; // link to next next one, skip this duplicate
    22                 duplicate.next = null;
    23             }
    24             else
    25                 cursor = cursor.next;
    26             
    27         }
    28         
    29         return head;
    30     }
    31 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    制作 MarkText 的导航栏和动画背景
    某雅互动静态页面
    html5 拖拽及用 js 实现拖拽
    九宫格
    phaser3 入门实例——收集星星游戏
    Flexbox Froggy:练习 Flex 布局的小游戏
    JS30
    ElasticSearch
    JVM
    jstack命令的使用
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7883014.html
Copyright © 2011-2022 走看看