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中值得一做的题的更多相关文章

  1. 用Javascript方式实现LeetCode中的算法(更新中)

    前一段时间抽空去参加面试,面试官一开始让我做一道题,他看完之后,让我回答一下这个题的时间复杂度并优化一下,当时的我虽然明白什么是时间复杂度,但不知道是怎么计算的,一开局出师不利,然后没然后了,有一次我 ...

  2. Leetcode中字符串总结

    本文是个人对LeetCode中字符串类型题目的总结,纯属个人感悟,若有不妥的地方,欢迎指出. 一.有关数字 1.数转换 题Interger to roman和Roman to integer这两题是罗 ...

  3. 值得一做》关于双标记线段树两三事BZOJ 1798 (NORMAL-)

    这是一道双标记线段树的题,很让人很好的预习/学习/复习线段树,我不知道它能让别人学习什么,反正让我对线段树的了解更加深刻. 题目没什么好讲的,程序也没什么好讲的,所以也没有什么题解,但是值得一做 给出 ...

  4. leetcode中,代码怎样调试,创造本地执行环境

    初次接触leetcode,是我在一个招聘站点上看的,这个OJ真有那么厉害吗? 这几天在这个OJ上做了几道题,发现他的几个特点,1.题目不难(相对于ACM来说,我被ACM虐到至今无力),评判没那么苛刻, ...

  5. codefroces中的病毒,这题有很深的trick,你能解开吗?

    大家好,欢迎阅读周末codeforces专题. 我们今天选择的问题是contest 1419的C题,目前有接近8000的人通过了本题.今天这题的难度不大,但是真的很考验思维,一不小心就会踩中陷阱,我个 ...

  6. 动态规划以及在leetcode中的应用

    之前只是知道动态规划是通过组合子问题来解决原问题的,但是如何分析,如何应用一直都是一头雾水.最近在leetcode中发现有好几道题都可以用动态规划方法进行解决,就此做下笔录. 动态规划:应用于子问题重 ...

  7. C++11 中值得关注的几大变化(网摘)

    C++11 中值得关注的几大变化(详解) 原文出处:[陈皓 coolshell] 源文章来自前C++标准委员会的 Danny Kalev 的 The Biggest Changes in C++11 ...

  8. C++中try_catch_throw的做异常处理

    C++中try_catch_throw的做异常处理 选择异常处理的编程方法的具体原因如下: . 把错误处理和真正的工作分开来: . 代码更易组织,更清晰,复杂的工作任务更容易实现: . 毫无疑问,更安 ...

  9. Leetcode 春季打卡活动 第一题:225. 用队列实现栈

    Leetcode 春季打卡活动 第一题:225. 用队列实现栈 Leetcode 春季打卡活动 第一题:225. 用队列实现栈 解题思路 这里用了非常简单的思路,就是在push函数上做点操作,让队头总 ...

随机推荐

  1. 关于JavaScript(脚本语言)

    1.typeof运算符:判断一个对象是否是什么类型,返回“” 一.数字类型(Number) 1.javascript不擅长计算,不能用于浮点数的计算.如:var a = 0.2; var b = 0. ...

  2. C# 操作SQL Server 公共库

    基本够用,存一下,以后找起来方便 public abstract class DB { //数据库连接字符串(config来配置) protected static string connection ...

  3. Mac新手必看教程—让你离熟练操作mac只差十分钟

    本文收录于:风云社区(提供各类mac软件资源下载) 本文源自:什么值得买 无论轻薄办公本.还是赶超台式性能的游戏本,关注#笔记本攻略#栏目,解决笔记本电脑从选购到使用的各种问题. 引子 大部分用户接触 ...

  4. React 记录(6)

    React文档:https://www.reactjscn.com/docs/react-component.html 慢慢学习:对照教程文档,逐句猜解,截图 React官网:https://reac ...

  5. 第四节:Task的启动的四种方式以及Task、TaskFactory的线程等待和线程延续的解决方案

    一. 背景 揭秘: 在前面的章节介绍过,Task出现之前,微软的多线程处理方式有:Thread→ThreadPool→委托的异步调用,虽然也可以基本业务需要的多线程场景,但它们在多个线程的等待处理方面 ...

  6. maven多个web模块进行合并

    原文地址: https://blog.csdn.net/u011666411/article/details/77160907

  7. $A,B$ 实对称 $\ra\tr((AB)^2)\leq \tr(A^2B^2)$

    设 $A,B$ 是 $n$ 阶实对称矩阵. 试证: $\tr((AB)^2)\leq \tr(A^2B^2)$. 又问: 等号何时成立? 证明:  由  $$\bex  \sum_i \sez{\su ...

  8. PL/SQl编程 基本语法

    /*输出hello world*/ DECLARE BEGIN DBMS_OUTPUT.PUT_LINE('Hello World'); END; --set serveroutput on; /** ...

  9. hiho 1097 最小生成树一·Prim算法 (最小生成树)

    题目: 时间限制:10000ms 单点时限:1000ms 内存限制:256MB   描述 最近,小Hi很喜欢玩的一款游戏模拟城市开放出了新Mod,在这个Mod中,玩家可以拥有不止一个城市了! 但是,问 ...

  10. Docker入门-docker-compose使用(二)

    Docker  Docker容器大行其道,直接通过 docker pull + 启动参数的方式运行比较麻烦, 可以通过docker-compose插件快速创建容器 1.安装docker-compose ...