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: Element.getBoundingClientRect() 获取元素在网页上的坐标位置

    来自:https://blog.csdn.net/weixin_42895400/article/details/81811095?utm_source=blogxgwz1 Element.getBo ...

  2. 三步解决fiddler升级后https无法通过证书验证问题

    有时候使用fiddler时,https页面会出现错误提示,我们可以这样设置来避免错误 第一步:去掉https的抓取 Tools>Option 去掉Capture HTTPS CONNECTs 的 ...

  3. js深拷贝

    // 判断是否为对象 function isObject(o) { return (typeof o === 'object' || typeof o === 'function') &&am ...

  4. JavaScript对象 Object类型基础

    前言 JavaScript 对象是整个语言学习的一个难点.本文主要带大家入门学习Object知识 对象定义 javascript的基本数据类型包括undefined.null.boolean.stri ...

  5. css中font-size为0的妙用(消除内联元素间的间隔)

    前言 <div> <input type="text"> <input type="button" value="提交& ...

  6. 轴对称 Navier-Stokes 方程组的点态正则性准则 I

    在 [Lei, Zhen; Zhang, Qi. Criticality of the axially symmetric Navier-Stokes equations. Pacific J. Ma ...

  7. Hough transform(霍夫变换)

    主要内容: 1.Hough变换的算法思想 2.直线检测 3.圆.椭圆检测 4.程序实现 一.Hough变换简介 Hough变换是图像处理中从图像中识别几何形状的基本方法之一.Hough变换的基本原理在 ...

  8. ES--07

    61.索引管理_快速上机动手实战创建.修改以及删除索引 课程大纲 1.为什么我们要手动创建索引? 2.创建索引 创建索引的语法 PUT /my_index{ "settings": ...

  9. 手把手教你写vue插件并发布(一)

    vue的插件开发 这篇文章较长,需要一定的阅读时间.这里有一份改善版本的插件笔记,在一个项目下完成开发.测试.发布的全过程.https://www.cnblogs.com/adouwt/p/96555 ...

  10. iOS 新建xib文件时,最外层view的约束问题

    今天用在利用xib实例化view 时, 生成的view的自动布局总是用问题.具体来说,宽和高都不能和父view正确变化.仔细检查,发现下图: 注意这里右上角的Autoresizing部分,并没有设置正 ...