leetcode 21-30 easy
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(INT_MIN);
ListNode *tail=&dummy;
while(l1 && l2)
{
if(l1->val<l2->val)
{
tail->next=l1;
l1=l1->next; }
else
{
tail->next=l2;
l2=l2->next;
}
tail=tail->next;
} //谁没结束就补充谁
tail->next=l1?l1:l2;
return dummy.next;
}
};
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
def mergeTwoLists1(self, l1, l2):
dummy = cur = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return dummy.next # recursively
def mergeTwoLists2(self, l1, l2):
if not l1 or not l2:
return l1 or l2
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2 # in-place, iteratively
def mergeTwoLists(self, l1, l2):
if None in (l1, l2):
return l1 or l2
dummy = cur = ListNode(0)
dummy.next = l1
while l1 and l2:
if l1.val < l2.val:
l1 = l1.next
else:
nxt = cur.next
cur.next = l2
tmp = l2.next
l2.next = nxt
l2 = tmp
cur = cur.next
cur.next = l1 or l2
return dummy.next
26. Remove Duplicates from Sorted Array
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2], Your function should return length =2
, with the first two elements ofnums
being1
and2
respectively. It doesn't matter what you leave beyond the returned length.Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length =5
, with the first five elements ofnums
being modified to0
,1
,2
,3
, and4
respectively. It doesn't matter what values are set beyond the returned length.Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
C++
int removeDuplicates(vector<int>& nums) {
int i = ;
for (int n : nums)
if (!i || n > nums[i-])
nums[i++] = n;
return i;
}
python
from collections import OrderedDict
class Solution(object):
def removeDuplicates(self, nums): nums[:] = OrderedDict.fromkeys(nums).keys()
return len(nums) ###########
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if not A:
return 0
end = len(A)
read = 1
write = 1
while read < end:
if A[read] != A[read-1]:
A[write] = A[read]
write += 1
read += 1
return write
28、Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1Clarification:
What should we return when
needle
is an empty string? This is a great question to ask during an interview.For the purpose of this problem, we will return 0 when
needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
C++
//暴力算法
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if (!n) return ; for (int i = ; i < m - n + ; i++) {
int j = ;
for (; j < n; j++) {
if (haystack[i + j] != needle[j]) {
break;
}
}
if (j == n) return i;
}
return -;
}
}; //KMP
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if (!n) {
return 0;
}
vector<int> lps = kmpProcess(needle);
for (int i = 0, j = 0; i < m; ) {
if (haystack[i] == needle[j]) {
i++;
j++;
}
if (j == n) {
return i - j;
}
if ((i < m) && (haystack[i] != needle[j])) {
if (j) {
j = lps[j - 1];
}
else {
i++;
}
}
}
return -1;
}
private:
vector<int> kmpProcess(string& needle) {
int n = needle.length();
vector<int> lps(n, 0);
for (int i = 1, len = 0; i < n; ) {
if (needle[i] == needle[len]) {
lps[i++] = ++len;
} else if (len) {
len = lps[len - 1];
} else {
lps[i++] = 0;
}
}
return lps;
}
};
leetcode 21-30 easy的更多相关文章
- 2017年1月4日 星期三 --出埃及记 Exodus 21:30
2017年1月4日 星期三 --出埃及记 Exodus 21:30 However, if payment is demanded of him, he may redeem his life by ...
- 2018-10-13 21:30:51 conversion of number systems
2018-10-13 21:30:51 c language 二进制.八进制和十六进制: 1) 整数部分 十进制整数转换为 N 进制整数采用“除 N 取余,逆序排列”法. 十进制数字 36926 转 ...
- Leetcode 21. Merge Two Sorted Lists(easy)
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t ...
- # 蜗牛慢慢爬 LeetCode 21. Merge Two Sorted Lists [Difficulty: Easy]
题目 Merge two sorted linked lists and return it as a new list. The new list should be made by splicin ...
- [leetcode] 21. Merge Two Sorted Lists (Easy)
合并链表 Runtime: 4 ms, faster than 100.00% of C++ online submissions for Merge Two Sorted Lists. class ...
- LeetCode Linked List Easy 21. Merge Two Sorted Lists
Description Merge two sorted linked lists and return it as a new list. The new list should be made b ...
- [Leetcode][Python]30: Substring with Concatenation of All Words
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 30: Substring with Concatenation of All ...
- 剑桥offer(21~30)
21.题目描述 输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba. 还不 ...
- 【剑指Offer】俯视50题之21 - 30题
面试题21包括min函数的栈 面试题22栈的压入.弹出序列 面试题23从上往下打印二叉树 面试题24二叉搜索树的后序遍历序列 面试题25二叉树中和为某一值的路径 面试题26复杂链表的复制 ...
- [LeetCode] 21. Merge Two Sorted Lists 混合插入有序链表
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t ...
随机推荐
- @Value取值为NULL的解决方案
在spring mvc架构中,如果希望在程序中直接使用properties中定义的配置值,通常使用一下方式来获取: @Value("${tag}") private String ...
- wpf关闭窗口弹出是否确认关闭的提示
if (MessageBox.Show("是否退出系统?", "退出系统?", MessageBoxButton.OKCancel, MessageBoxIma ...
- 玩转大数据系列之Apache Pig高级技能之函数编程(六)
原创不易,转载请务必注明,原创地址,谢谢配合! http://qindongliang.iteye.com/ Pig系列的学习文档,希望对大家有用,感谢关注散仙! Apache Pig的前世今生 Ap ...
- error C2440 “static_cast” 无法从“void (__thiscall C* )(void)...
1.VC6中,说可以把函数在头文件中定义为:afx_msg void OnProgress()这样 但是在VS2005及以上,要求很严格,必须函数返回值为LRESULT类型,所以在VS2005及以上, ...
- 2018-8-10-VisualStudio-使用三个方法启动最新-C#-功能
title author date CreateTime categories VisualStudio 使用三个方法启动最新 C# 功能 lindexi 2018-08-10 19:16:52 +0 ...
- 6.Spring【AOP】XML方式
1.AOP术语 1. Joinpoint(连接点):所谓连接点是指那些被拦截到的点.在spring中,这些点指的是方法,因为spring只支持方法类型的连接点 2. Pointcut(切入点):所谓切 ...
- php连接数据库插入数据
<form action="updata.php" method="post"> 姓名:<input type="text" ...
- DSMM之数据处理安全
一.背景 数据安全生命周期分为采集.传输.存储.处理.交换.销毁几个阶段,其中数据处理阶段是整个周期的核心阶段,数据处理安全与否直接关系到整体数据安全.那么今天分享内容就是数据处理安全的相关要求和实现 ...
- thinkphp+ajax 实现点击加载更多数据
https://blog.csdn.net/a898712940/article/details/78545599?utm_source=blogxgwz8 适用范围:thinkphp3.2和thin ...
- Django项目: 项目环境搭建 ---- 一、创建django项目
项目环境搭建 一.创建django项目 1.创建python虚拟环境 在虚拟机上创建python虚拟环境,因为实际项目部署,实在linux mkvirtualenv -p /usr/bin/pytho ...