Leetcode中值得一做的题
3.longest substring
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
4. Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
存在log(min(n,m))的解法
这个代码太复杂了,现场不容易想起来,看这个:链接
This problem is notoriously hard to implement due to all the corner cases. Most implementations consider odd-lengthed and even-lengthed arrays as two different cases and treat them separately. As a matter of fact, with a little mind twist. These two cases can be combined as one, leading to a very simple solution where (almost) no special treatment is needed. First, let's see the concept of 'MEDIAN' in a slightly unconventional way. That is: "if we cut the sorted array to two halves of EQUAL LENGTHS, then
median is the AVERAGE OF Max(lower_half) and Min(upper_half), i.e. the
two numbers immediately next to the cut".
For example, for [ ], we make the cut between and : [ / ]
then the median = (+)/. Note that I'll use '/' to represent a cut, and (number / number) to represent a cut made through a number in this article. for [ ], we make the cut right through like this: [ (/) ] Since we split into two halves, we say now both the lower and upper subarray contain . This notion also leads to the correct answer: ( + ) / = ; For convenience, let's use L to represent the number immediately left to the cut, and R the right counterpart. In [2 3 5 7], for instance, we have L = 3 and R = 5, respectively. We observe the index of L and R have the following relationship with the length of the array N: N Index of L / R
/
/
/
/
/
/
/
/
It is not hard to conclude that index of L = (N-)/, and R is at N/. Thus, the median can be represented as (L + R)/ = (A[(N-)/] + A[N/])/
To get ready for the two array situation, let's add a few imaginary 'positions' (represented as #'s) in between numbers, and treat numbers as 'positions' as well. [ ] -> [# # # # #] (N = )
position index (N_Position = ) [ ]-> [# # # # # #] (N = )
position index (N_Position = )
As you can see, there are always exactly *N+ 'positions' regardless of length N. Therefore, the middle cut should always be made on the Nth position (-based). Since index(L) = (N-)/ and index(R) = N/ in this situation, we can infer that index(L) = (CutPosition-)/, index(R) = (CutPosition)/. Now for the two-array case: A1: [# # # # # #] (N1 = , N1_positions = ) A2: [# # # # #] (N2 = , N2_positions = )
Similar to the one-array problem, we need to find a cut that divides the two arrays each into two halves such that "any number in the two left halves" <= "any number in the two right
halves".
We can also make the following observations: There are 2N1 + 2N2 + position altogether. Therefore, there must be exactly N1 + N2 positions on each side of the cut, and positions directly on the cut. Therefore, when we cut at position C2 = K in A2, then the cut position in A1 must be C1 = N1 + N2 - k. For instance, if C2 = , then we must have C1 = + - C2 = . [# # # # (/) # #] [# / # # #]
When the cuts are made, we'd have two L's and two R's. They are L1 = A1[(C1-)/]; R1 = A1[C1/];
L2 = A2[(C2-)/]; R2 = A2[C2/];
In the above example, L1 = A1[(-)/] = A1[] = ; R1 = A1[/] = A1[] = ;
L2 = A2[(-)/] = A2[] = ; R2 = A1[/] = A1[] = ;
Now how do we decide if this cut is the cut we want? Because L1, L2 are the greatest numbers on the left halves and R1, R2 are the smallest numbers on the right, we only need L1 <= R1 && L1 <= R2 && L2 <= R1 && L2 <= R2
to make sure that any number in lower halves <= any number in upper halves. As a matter of fact, since
L1 <= R1 and L2 <= R2 are naturally guaranteed because A1 and A2 are sorted, we only need to make sure: L1 <= R2 and L2 <= R1. Now we can use simple binary search to find out the result. If we have L1 > R1, it means there are too many large numbers on the left half of A1, then we must move C1 to the left (i.e. move C2 to the right);
If L2 > R1, then there are too many large numbers on the left half of A2, and we must move C2 to the left.
Otherwise, this cut is the right one.
After we find the cut, the medium can be computed as (max(L1, L2) + min(R1, R2)) / ;
Two side notes: A. since C1 and C2 can be mutually determined from each other, we might as well select the shorter array (say A2) and only move C2 around, and calculate C1 accordingly. That way we can achieve a run-time complexity of O(log(min(N1, N2))) B. The only edge case is when a cut falls on the 0th(first) or the 2Nth(last) position. For instance, if C2 = 2N2, then R2 = A2[*N2/] = A2[N2], which exceeds the boundary of the array. To solve this problem, we can imagine that both A1 and A2 actually have two extra elements, INT_MAX at A[-] and INT_MAX at A[N]. These additions don't change the result, but make the implementation easier: If any L falls out of the left boundary of the array, then L = INT_MIN, and if any R falls out of the right boundary, then R = INT_MAX. I know that was not very easy to understand, but all the above reasoning eventually boils down to the following concise code: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int N1 = nums1.size();
int N2 = nums2.size();
if (N1 < N2) return findMedianSortedArrays(nums2, nums1); // Make sure A2 is the shorter one. if (N2 == ) return ((double)nums1[(N1-)/] + (double)nums1[N1/])/; // If A2 is empty int lo = , hi = N2 * ;
while (lo <= hi) {
int mid2 = (lo + hi) / ; // Try Cut 2
int mid1 = N1 + N2 - mid2; // Calculate Cut 1 accordingly double L1 = (mid1 == ) ? INT_MIN : nums1[(mid1-)/]; // Get L1, R1, L2, R2 respectively
double L2 = (mid2 == ) ? INT_MIN : nums2[(mid2-)/];
double R1 = (mid1 == N1 * ) ? INT_MAX : nums1[(mid1)/];
double R2 = (mid2 == N2 * ) ? INT_MAX : nums2[(mid2)/]; if (L1 > R2) lo = mid2 + ; // A1's lower half is too big; need to move C1 left (C2 right)
else if (L2 > R1) hi = mid2 - ; // A2's lower half too big; need to move C2 left.
else return (max(L1,L2) + min(R1, R2)) / ; // Otherwise, that's the right cut.
}
return -;
}
If you have any suggestions to make the logic and implementation even more cleaner. Please do let me know!
11. Container With Most Water
主要是一个贪心的思想,从小边往里面靠
18. 4Sum
2 Sum, 3 Sum的加强版
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n=nums.size();
sort(nums.begin(),nums.end());
int i,j,k;
int f1=,f2=,f3=;
int b1=,b2=,b3=;
vector<vector<int>> fans;
int tot=;
for(i=;i<n;i++){
int w1=target-nums[i];
for(j=i+;j<n;j++){
int w2=w1-nums[j];
f1=j+;
b1=n-;
while(f1<b1){
int sum=nums[f1]+nums[b1];
if(sum==w2){ //符合要求
vector<int> ans(,);
ans[]=nums[i];
ans[]=nums[j];
ans[]=nums[f1];
ans[]=nums[b1];
fans.push_back(ans);
while(f1<b1&&ans[]==nums[f1]) f1++; //相同的可以不算进去了
while(f1<b1&&ans[]==nums[f1]) b1--;
}
else if(sum<w2){
f1++;
}
else b1--;
}
while(j + <n && nums[j + ] == nums[j]) ++j;
}
while (i + <n && nums[i + ] == nums[i]) ++i;
}
return fans;
}
};
快速排序,第k小的数字
快排流程参考
int partition(vector<int> &num,int left,int right)
{
int index=left;
int pivot=num[right];
for(int i=left;i<right;i++){
if (num[i]<pivot)
{
swap(num[i], num[index]);
index++;
}
}
swap(num[right], num[index]);
return index;
}
void sort(vector<int> &num,int left,int right)
{
if(left>right) return;
int pindex = partition(num, left, right);
sort(num, left, pindex - );
sort(num, pindex + , right);
}
int sortk(vector<int> &num,int left,int right,int k) //k smallest number
{
if(right==left) return num[right];
int index = partition(num, left, right);
if(index-left+==k) return num[k];
else if(index-left+>k)
sortk(num, left, index - ,k);
else sortk(num, index + , right,k);
}
33 折过的二分查找
public class Solution {
public int search(int[] nums, int target) {
int start = ;
int end = nums.length - ;
while (start <= end){
int mid = (start + end) / ;
if (nums[mid] == target)
return mid; if (nums[start] <= nums[mid]){
if (target < nums[mid] && target >= nums[start])
end = mid - ;
else
start = mid + ;
} if (nums[mid] <= nums[end]){
if (target > nums[mid] && target <= nums[end])
start = mid + ;
else
end = mid - ;
}
}
return -;
}
}
236 LCA
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
return !left ? right : !right ? left : root;
}
621
字典树
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include <sstream>
using namespace std;
#define MOD 1000000007
const int INF=;
const double eps=1e-;
typedef long long ll;
#define cl(a) memset(a,0,sizeof(a))
#define ts printf("*****\n"); struct Trie
{
int ch[][];
int sz=;
int val[];
Tire()
{
sz=;
memset(ch[],,sizeof(ch[]));
}
void TireInsert(char *s,int v)
{
int u=;
int len=strlen(s);
for(int i=;i<len;i++){
int c=s[i]-'a';
if(!ch[u][c]){
memset(ch[sz],,sizeof(ch[sz]));
val[sz]=;
ch[u][c]=sz++;
}
u=ch[u][c];
}
val[u]=v;
}
void Tirecheck(char *s)
{
int u=;
int len=strlen(s);
for(int i=;i<len;i++){
int c=s[i]-'a';
if(!ch[u][c]){
printf("can not find such string\n");
return;
}
u=ch[u][c];
}
string w="";
dfs(u, s,w);
}
void dfs(int u,char *s,string w)
{
if(val[u]==){
cout<<s<<w<<endl;
}
for(int i=;i<;i++){
if(ch[u][i]){
char k='a'+i;
string o=w+k;
dfs(ch[u][i],s,o);
}
}
}
}; int main()
{
int a[]={,,,,,,};
vector<int> nums;
for(int i=;i<;i++){
nums.push_back(a[i]);
}
char s1[]="minaro";
char s2[]="mingugua";
char s3[]="ming";
char s4[]="min";
char s5[]="maxpro";
char s6[]="maxgugua";
char s7[]="maxg";
char s8[]="max"; Trie t;
t.TireInsert(s1,);
t.TireInsert(s2,);
t.TireInsert(s3,);
t.TireInsert(s4,);
t.TireInsert(s5,);
t.TireInsert(s6,);
t.TireInsert(s7,);
t.TireInsert(s8,);
cout<<t.sz<<endl;
char ss1[]="min";
t.Tirecheck(ss1); }
146 LRU 链接
Leetcode中值得一做的题的更多相关文章
- 用Javascript方式实现LeetCode中的算法(更新中)
前一段时间抽空去参加面试,面试官一开始让我做一道题,他看完之后,让我回答一下这个题的时间复杂度并优化一下,当时的我虽然明白什么是时间复杂度,但不知道是怎么计算的,一开局出师不利,然后没然后了,有一次我 ...
- Leetcode中字符串总结
本文是个人对LeetCode中字符串类型题目的总结,纯属个人感悟,若有不妥的地方,欢迎指出. 一.有关数字 1.数转换 题Interger to roman和Roman to integer这两题是罗 ...
- 值得一做》关于双标记线段树两三事BZOJ 1798 (NORMAL-)
这是一道双标记线段树的题,很让人很好的预习/学习/复习线段树,我不知道它能让别人学习什么,反正让我对线段树的了解更加深刻. 题目没什么好讲的,程序也没什么好讲的,所以也没有什么题解,但是值得一做 给出 ...
- leetcode中,代码怎样调试,创造本地执行环境
初次接触leetcode,是我在一个招聘站点上看的,这个OJ真有那么厉害吗? 这几天在这个OJ上做了几道题,发现他的几个特点,1.题目不难(相对于ACM来说,我被ACM虐到至今无力),评判没那么苛刻, ...
- codefroces中的病毒,这题有很深的trick,你能解开吗?
大家好,欢迎阅读周末codeforces专题. 我们今天选择的问题是contest 1419的C题,目前有接近8000的人通过了本题.今天这题的难度不大,但是真的很考验思维,一不小心就会踩中陷阱,我个 ...
- 动态规划以及在leetcode中的应用
之前只是知道动态规划是通过组合子问题来解决原问题的,但是如何分析,如何应用一直都是一头雾水.最近在leetcode中发现有好几道题都可以用动态规划方法进行解决,就此做下笔录. 动态规划:应用于子问题重 ...
- C++11 中值得关注的几大变化(网摘)
C++11 中值得关注的几大变化(详解) 原文出处:[陈皓 coolshell] 源文章来自前C++标准委员会的 Danny Kalev 的 The Biggest Changes in C++11 ...
- C++中try_catch_throw的做异常处理
C++中try_catch_throw的做异常处理 选择异常处理的编程方法的具体原因如下: . 把错误处理和真正的工作分开来: . 代码更易组织,更清晰,复杂的工作任务更容易实现: . 毫无疑问,更安 ...
- Leetcode 春季打卡活动 第一题:225. 用队列实现栈
Leetcode 春季打卡活动 第一题:225. 用队列实现栈 Leetcode 春季打卡活动 第一题:225. 用队列实现栈 解题思路 这里用了非常简单的思路,就是在push函数上做点操作,让队头总 ...
随机推荐
- java.io.FileNotFoundException:my-release-key.keyStore拒绝访问
安卓生成APK的时候,生成密钥的时候报java.io.FileNotFoundException:my-release-key.keyStore拒绝访问的错误 这是因为权限问题:你的jdk目录在c盘, ...
- linux镜像下载
https://blog.csdn.net/qq_42570879/article/details/82853708
- VMWare的host-only/bridged/NAT连接图文介绍
1 VMware简介 VMWare虚拟机软件是一个“虚拟PC”软件,它使我们可以在一台机器上同时运行二个或更多Windows.Linux等系统. 如果我们需要使用多个系统的话,传统的方式有两种: .使 ...
- scala使用slick查询的全过程(使用cass class)
1. 首先导包 <dependency> <groupId>com.typesafe.slick</groupId> <artifactId>slick ...
- Concurrent下的线程安全集合
1.ArrayBlockingQueue ArrayBlockingQueue是由数组支持的线程安全的有界阻塞队列,此队列按 FIFO(先进先出)原则对元素进行排序.这是一个典型的“有界缓存区”,固定 ...
- 使用node.js 脚手架搭建Vue项目
1.安装node.js https://nodejs.org/zh-cn/ 下载安装node.js 在命令行测试 node -v 输出版本号说明安装成功 2.使用npm更新安装cpnm npm ins ...
- Mysql中设置指定IP的特定用户及特定权限
创建用户:格式:grant select on 数据库.* to 用户名@登录主机 identified by '密码' 举例: 例 1:增加一个用户 test1 密码为 abc,让他可以在任何主机上 ...
- 肺结节CT影像特征提取(四)——肺结节CT影像特征提取MATLAB代码实现
之前的文章讲述了肺结节CT影像数据特征提取算法及基于MATLAB GUI设计的肺结节CT影像特征提取系统.本文将讲述几个主要部分的代码实现,分别是预处理.灰度特征提取.纹理特征提取.形态特征提取数据. ...
- HTTP协议08-请求首部字段
请求首部字段 请求首部字段是从客户端往服务器端发送请求报文中所使用的字段,用于补充请求的附加信息.客户端信息,对响应内容相关的优先级等内容 1)Accept 通知服务器,用户代理能够处理的媒体类型及媒 ...
- 第三周 数据分析之概要 Pandas库入门
Pandas库介绍: Pandas库引用:Pandas是Python第三方库,提供高性能易用数据类型和分析工具 import pandas as pd Pandas基于NumPy实现,常与NumPy和 ...