leetcode题解日练--2016.6.20

来源:互联网 发布:华为 媒体算法工程师 编辑:程序博客网 时间:2024/05/18 11:05

编程新手,尽量保证每天至少3道leetcode题,仅此记录学习的一些题目答案与思路,尽量用多种思路来分析解决问题,不足之处还望指出。

今日题目:1、交换链表相邻的节点;2、交换字符串的元音;3、房子小偷

24. Swap Nodes in Pairs | Difficulty: Easy

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
题意:给一个单向链表,需要交换相邻的两个节点,不能修改链表的节点。
思路:
1、假设只有a->b->c->d四个节点,目的是通过交换得到b->a->d->c,那么我们可以以每两个节点为一个单元,对于a、b而言,需要将a指向b->next,然后将b指向a,pre最初是头节点,用它指向链表头b,然后pre置为a(前一单元的后节点),这个时候链表变成了self->b->a(pre)->c->d。再到第二个单元的时候,c就是之前的pre->next,d就是c->next,然后之后每一次操作就是前一单元的后节点指向后一单元的后节点,后一单元的后节点指向后一单元的前节点,后一单元的前节点指向后后一单元的前节点。pre其实记录的是前一单元的后节点。
代码:
C++

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:   ListNode* swapPairs(ListNode* head) {       ListNode** pp = &head;       ListNode *a,*b;       if(head==NULL||head->next==NULL)  return head;       while((a=*pp)&&(b=a->next))       {            a->next = b->next;            b->next=a;            //pp是一个二级指针,里面存的是节点的地址,*pp是这个节点的本身,pp是存储的节点的地址            //*pp=b是用来将pp里面存的节点和b节点划上等号,最开始是将head与b划等号,相当于确定head节点,之后每一次都是将(a->next)与b划等号            *pp=b;            //pp=&(a->next)是将每次pp设置为a->next,这样下次开是下次的循环            pp=&(a->next);       }       return head;   }};

结果:4ms

python# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def swapPairs(self, head):    pre, pre.next = self, head    while pre.next and pre.next.next:        a = pre.next        b = a.next        pre.next, b.next, a.next = b, a, b.next        pre = a    return self.next

结果:60 ms Your runtime beats 18.04% of pythonsubmissions.

第二次刷代码

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* swapPairs(ListNode* head) {        //not bixu        if(head==NULL || head->next==NULL)  return head;        ListNode*newHead = new ListNode(INT_MIN);        ListNode* pre=newHead,*next;        pre->next = head;        ListNode*cur = head;        while(cur && cur->next)        {            next = cur->next;            pre->next = cur->next;            cur->next = next->next;            next->next = cur;            pre = cur;            cur = cur->next;        }        return newHead->next;    }};

结果:4ms

另外一种思路

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* swapPairs(ListNode* head) {        if(head==NULL || head->next==NULL)  return head;        ListNode*newHead = new ListNode(INT_MIN);        ListNode*cur = newHead;        newHead->next = head->next;        while(head && head->next)        {            ListNode *Next =head->next->next;;            ListNode* NextNext=NULL;            head->next->next = head;            //A->B->C->D,D不为空给其赋值            if(Next!=NULL && Next->next)  NextNext = Next->next;            //根据D有无元素改变A的指向            if(NextNext==NULL) head->next = Next;            else head->next = NextNext;            head = Next;        }        return newHead->next;    }};

结果:4ms

345. Reverse Vowels of a String | Difficulty: Easy

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = “hello”, return “holle”.

Example 2:
Given s = “leetcode”, return “leotcede”.
题意:将数组中的元音逆序。
思路:一前一后两个指针,依次去找元音,只要找到了且前指针小于后指针就交换两个指针,终止条件是前指针大于等于后指针。
c++

class Solution {public:    string reverseVowels(string s) {        auto p1 = s.begin(), p2 = s.end() - 1;        string vowels = "aeiouAEIOU";        while(p1 < p2) {            while((vowels.find(*p1) == -1) && (p1 < p2)) p1++;            while((vowels.find(*p2) == -1) && (p1 < p2)) p2--;            if(p1 < p2) swap(*p1, *p2);            p1++;            p2--;        }        return s;    }};

结果:16ms Your runtime beats 47.19% of cppsubmissions.
python的实现相对简单,首先找到有哪些元音,然后用正则表达式里面的re.sub来进行替换,用到了lambda表达式

class Solution(object):    def reverseVowels(self, s):        vowels = re.findall('(?i)[aeiou]', s)        return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)

结果:100ms Your runtime beats 93.59% of pythonsubmissions.
或者用正则先匹配出哪些位置的元素是元音,然后再交换它们

class Solution(object):    def reverseVowels(self,s):        vowels = set(re.findall('[AEIOUaeiou]', s))        find_all = [idx for idx,e in enumerate(s) if e in vowels]        s = list(s)        for item in range(len(find_all)/2):            s[find_all[item]],s[find_all[len(find_all)-1-item]] =  s[find_all[len(find_all)-1-item]],s[find_all[item]]        return ''.join(s)

结果:116ms Your runtime beats 76.40% of pythonsubmissions.

198. House Robber | Difficulty: Easy

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

题意:一连串非负的整数,不能取连续相邻的两个元素,如何取才能取得最大的累加和。
思路:
f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )
代码:
c++

class Solution {public:    int rob(vector<int>& nums) {        int cur = 0,pre = 0;        for(int i=0;i<nums.size();i++)        {            int tmp = max(pre+nums[i],cur);            pre = cur;            cur = tmp;        }        return cur;    }};

结果: 0ms

class Solution:    def rob(self, nums):        last, now = 0, 0        for i in nums: last, now = now, max(last + i, now)        return now

结果:60ms Your runtime beats 17.18% of pythonsubmissions.
参考资料:
1、https://leetcode.com/discuss/42398/python-solution-3-lines

0 0
原创粉丝点击