leetcode题解日练--2016.6.20

2024-03-06 10:48
文章标签 leetcode 20 题解 日练 2016.6

本文主要是介绍leetcode题解日练--2016.6.20,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

编程新手,尽量保证每天至少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, headwhile pre.next and pre.next.next:a = pre.nextb = a.nextpre.next, b.next, a.next = b, a, b.nextpre = areturn 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 bixuif(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, 0for 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

这篇关于leetcode题解日练--2016.6.20的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/779814

相关文章

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

哈希leetcode-1

目录 1前言 2.例题  2.1两数之和 2.2判断是否互为字符重排 2.3存在重复元素1 2.4存在重复元素2 2.5字母异位词分组 1前言 哈希表主要是适合于快速查找某个元素(O(1)) 当我们要频繁的查找某个元素,第一哈希表O(1),第二,二分O(log n) 一般可以分为语言自带的容器哈希和用数组模拟的简易哈希。 最简单的比如数组模拟字符存储,只要开26个c

系统架构师考试学习笔记第三篇——架构设计高级知识(20)通信系统架构设计理论与实践

本章知识考点:         第20课时主要学习通信系统架构设计的理论和工作中的实践。根据新版考试大纲,本课时知识点会涉及案例分析题(25分),而在历年考试中,案例题对该部分内容的考查并不多,虽在综合知识选择题目中经常考查,但分值也不高。本课时内容侧重于对知识点的记忆和理解,按照以往的出题规律,通信系统架构设计基础知识点多来源于教材内的基础网络设备、网络架构和教材外最新时事热点技术。本课时知识

leetcode-24Swap Nodes in Pairs

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode swapPairs(L

leetcode-23Merge k Sorted Lists

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeKLists

C++ | Leetcode C++题解之第393题UTF-8编码验证

题目: 题解: class Solution {public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num &

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return

【C++学习笔记 20】C++中的智能指针

智能指针的功能 在上一篇笔记提到了在栈和堆上创建变量的区别,使用new关键字创建变量时,需要搭配delete关键字销毁变量。而智能指针的作用就是调用new分配内存时,不必自己去调用delete,甚至不用调用new。 智能指针实际上就是对原始指针的包装。 unique_ptr 最简单的智能指针,是一种作用域指针,意思是当指针超出该作用域时,会自动调用delete。它名为unique的原因是这个