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 of nums being 1 and 2 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 of nums being modified to 0, 1, 2, 3, and 4 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: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

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的更多相关文章

  1. 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 ...

  2. 2018-10-13 21:30:51 conversion of number systems

    2018-10-13 21:30:51  c language 二进制.八进制和十六进制: 1) 整数部分 十进制整数转换为 N 进制整数采用“除 N 取余,逆序排列”法. 十进制数字 36926 转 ...

  3. 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 ...

  4. # 蜗牛慢慢爬 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 ...

  5. [leetcode] 21. Merge Two Sorted Lists (Easy)

    合并链表 Runtime: 4 ms, faster than 100.00% of C++ online submissions for Merge Two Sorted Lists. class ...

  6. 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 ...

  7. [Leetcode][Python]30: Substring with Concatenation of All Words

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 30: Substring with Concatenation of All ...

  8. 剑桥offer(21~30)

    21.题目描述 输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba.   还不 ...

  9. 【剑指Offer】俯视50题之21 - 30题

    面试题21包括min函数的栈  面试题22栈的压入.弹出序列  面试题23从上往下打印二叉树  面试题24二叉搜索树的后序遍历序列  面试题25二叉树中和为某一值的路径  面试题26复杂链表的复制  ...

  10. [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 ...

随机推荐

  1. PAT甲级——A1085 Perfect Sequence

    Given a sequence of positive integers and another positive integer p. The sequence is said to be a p ...

  2. 左神算法进阶班5_4设计可以变更的缓存结构(LRU)

    [题目] 设计一种缓存结构,该结构在构造时确定大小,假设大小为K,并有两个功能: set(key, value):将记录(key, value)插入该结构. get(key):返回key对应的valu ...

  3. myeclipse 无法部署项目到jboss服务器 部署不上去

    关于myeclipse部署项目到jboss点击add deployments没有反应的问题,如图 此处点击右键,选择add deployments没有反应,原因是默认的web-root folder为 ...

  4. if __name__=='__main__'使用场景,彻底明白

    本博中有一篇文章写了 if __name__=='__main__'的作用与原理http://www.cnblogs.com/fennudexiaoniao/p/7458324.html,但是好像似懂 ...

  5. Netty设置高低水位

    Configure high and low write watermarks   Server ServerBootstrap bootstrap = new ServerBootstrap(); ...

  6. css3之 过渡

    早期在Web中要实现动画效果,都是依赖于JavaScript或Flash来完成.但在CSS3中新增加了一个新的模块transition,它可以通过一些简单的CSS事件来触发元素的外观变化,让效果显得更 ...

  7. VC控件DateTimePicker使用方法

    出自http://www.cnblogs.com/52yixin/articles/2111299.html 使用DateTimePicker控件一般是获 取其时间替代手工输入带来的不便,而DateT ...

  8. HBase Ambari

  9. [转]深入WPF--Style

    Style 用来在类型的不同实例之间共享属性.资源和事件处理程序,您可以将 Style 看作是将一组属性值应用到多个元素的捷径. 这是MSDN上对Style的描述,翻译的还算中规中矩.Style(样式 ...

  10. odoo xml 时间搜索条件

    今年 <filter string="This Year" name="year" domain="[('date','<=', time ...