Wednesday, July 3, 2013

Remove Duplicates from Sorted Lists II @leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
这道题做了好久逻辑还是没对,总是漏掉一些东西,考虑得很复杂,看了别人的代码后有了一些启发。第一,用safeguard,就是在head前面加上一个头结点,避免处理head的情况。最后记得删掉。第二,就是平时可以先用自己复杂的逻辑把代码写出来,再对比别人的看如何把逻辑简化,这样就可以把代码简化,多做几次会形成一种直觉,下一次设计会快很多。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL) return head;
ListNode *G = new ListNode(INT_MIN);
G->next = head;
ListNode *cur = G, *pre = head;
while(pre!=NULL)
{
bool isDup = false;
while(pre->next!=NULL && pre->val == pre->next->val)
{
isDup = true;
pre = pre->next;
}
if(isDup)
{
pre = pre->next;
continue;
}
cur->next = pre;
cur = cur->next;
pre= pre->next;
}
cur->next = pre;
ListNode *temp = G->next;
delete G;
return temp;
}
};

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...