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. Codeforces Gym 101252D&&floyd判圈算法学习笔记

    一句话题意:x0=1,xi+1=(Axi+xi%B)%C,如果x序列中存在最早的两个相同的元素,输出第二次出现的位置,若在2e7内无解则输出-1. 题解:都不到100天就AFO了才来学这floyd判圈 ...

  2. 【强大精美的PS特效滤镜合集】Alien Skin Eye Candy for Mac 7.2.2.20

    [简介] Alien Skin Eye Candy for Mac 7.2.2 版本,支持最新的PhotoShop CC 2019.2018等版本,这是一款强大酷炫的PS特效滤镜合集,具有32种滤镜和 ...

  3. CMDB资产管理系统开发【day25】:需求分析

    本节内容 浅谈ITIL CMDB介绍 Django自定义用户认证 Restful 规范 资产管理功能开发 浅谈ITIL TIL即IT基础架构库(Information Technology Infra ...

  4. [物理学与PDEs]第1章第8节 静电场和静磁场 8.3 静磁场

    1. 静磁场: 由稳定电流形成的磁场. 2. 此时, Maxwell 方程组为 $$\beex \bea \Div{\bf D}&=\rho_f,\\ \rot {\bf E}&={\ ...

  5. Spring MVC 使用问题与解决--HTTP Status 500 - Servlet.init() for servlet springmvc threw exception

    1.HTTP Status 500 - Servlet.init() for servlet springmvc threw exception 解决 使用jre1.7 Spring4.3 2.spr ...

  6. css和css3弹性盒模型实现元素宽度(高度)自适应

    一.css实现左侧宽度固定右侧宽度自适应 1.定位 <!DOCTYPE html> <html lang="en"> <head> <me ...

  7. vue之简单组件例子

    <!-- 根组件 --> <!-- vue的模板内,所有内容要被一个根节点包含起来 --> <template> <div id="app" ...

  8. ES6 的 一些语法

    1,let 声明变量 let 声明的变量只能在let 的块级作用域中生效,也是为了弥补var声明变量的全局污染问题. var 声明变量有变量提升的作用,也就是在声明变量之前可以使用变量 console ...

  9. struts2简单入门-数据校验

    数据校验流程 校验数据的方式 重写execute方法在内部写校验代码 public class LoginAdminAction extends ActionSupport { private Use ...

  10. L1-Day1

    L1-Day11.我是一个网虫.(描述关系)[我的翻译]I am a net worm.[标准答案]I am a webaholic.[对比分析]我的worm是实实在在的虫子,本句话想表达的意思是对网 ...