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 ...
随机推荐
- JDK源码阅读--Hashtable
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable ...
- php构造方法(函数)基础
什么是构造函数呢?在回答这个问题之前,我们来看一个需求:我们在创建人类的对象时,是先把一个对象创建好后,再给他的年龄和姓名属性赋值,如果现在我要求,在创建人类的对象时,就指定这个对象的年龄和姓名,该怎 ...
- PAT甲级——A1081 Rational Sum
Given N rational numbers in the form numerator/denominator, you are supposed to calculate their sum. ...
- double转String
两种方式: 1.value = new DecimalFormat().format(double); 2.value = String.valueOf(double); 要相保留所有的double位 ...
- 表格Table好看的样式表
caption { padding: 0 0 5px 0; width: 700px; font: italic 11px "Trebuchet MS" , Verdana, Ar ...
- mvvmlight下passwordBox绑定的解决方法
在做公司的项目中,用到MVVMLight框架,需要做登陆注册的功能模块,但是在wpf中passwordBox没有内置绑定功能,因为出于安全的考虑.但是,博主又非常想要契合mvvm思想,一定要passw ...
- Linux下使用SSH命令行传输文件到远程服务器
目标:CentOS 7 调整 home分区 扩大 root分区 总体过程: 把/home内容备份,然后将/home文件系统所在的逻辑卷删除,扩大/root文件系统,新建/home ,恢复/home内容 ...
- 全面解析Spring中@ModelAttribute注解的用法
本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:全面解析Spring中@ModelAttribute注解的用法: @ModelAttribute注解用于将方法的参数或方法的返回值绑定到 ...
- xlwt/xlwt/Style.py excel样式源文件
from __future__ import print_function # -*- coding: windows-1252 -*- from . import Formatting from . ...
- org.apache.ibatis.executor.ExecutorException: No constructor found in xxxClass matching [java.lang.String, java.lang.Long, java.lang.String, java.lang.String, java.sql.Timestamp]
解决方案 为bean加上默认构造方法 public class User { private String username; private long id; private String sex; ...