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 ...
随机推荐
- Python中实现对list做减法操作介绍
Python中实现对list做减法操作介绍 这篇文章主要介绍了Python中实现对list做减法操作介绍,需要的朋友可以参考下 问题描述:假设我有这样两个list, 一个是list1,list1 = ...
- PAT甲级——A1084 Broken Keyboard
On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters ...
- Lucene 评分机制一
1. 评分公式 1.1 公式介绍 这个公式是Lucene实际计算时使用的公式,是由原型公式推导而来 tf(t in d) 表示某个term的出现频率,定义了term t出现在当前document d的 ...
- html常用标签详解5-表格标签
表格标签(如果有不对的,请大家多多指正.谢谢!) 1.总的表格标签概览 <table><!--表格标签start--> <caption></caption& ...
- Vue.nextTick()的介绍和使用场景
每次都很好奇这个干嘛的,然后百度之后还是不明白.今天就彻彻底底好好的弄明白这是干嘛的!! 首先看一下vue文档 nextTick(),是将回调函数延迟在下一次DOM更新数据后调用,简单的理解是:当数据 ...
- EPSG、SRID、WKT的概念
转自:http://www.cnblogs.com/jackdong/archive/2010/12/20/1911558.html EPSG:European Petroleum Survey Gr ...
- java文件配置MySQL
MybatisConfig.java文件 import com.alibaba.druid.pool.DruidDataSource; import com.xman.common.mybatis.S ...
- [转载] OpenCV2.4.3 CheatSheet学习(三)
四.图像处理(呵呵,重头戏来了) 1. 滤波 filter2D() 用核函数对图像做卷积. sepFilter2D() 用分解的核函数对图像做卷积. 首先,图像的每一行与一维的核kernelX做卷积: ...
- webServices学习二(小试牛刀。jdk 方式发布一个应用)
一.前提 1.用Jdk1.6.0_21以后的版本发布一个WebService服务. 2.与Web服务相关的类,都位于javax.jws.*包中. 1.主要类有: 1.@WebService - 它是 ...
- 2019-7-9-Roslyn-如何在-Target-引用-xaml-防止文件没有编译
title author date CreateTime categories Roslyn 如何在 Target 引用 xaml 防止文件没有编译 lindexi 2019-07-09 17:16: ...