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. MFC(1):vc6.0转vs2005出现的问题

     在将vc6.0程序转换到vs2005或者vs2008.vs2010时提示:error C2440: 'static_cast' : cannot convert from 'UINT (__this ...

  2. qt: 获取sql数据表的所有的字段;

    1. mysql 数据库: 转载: https://www.cnblogs.com/fuqia/p/8994080.html mysql安装成功后可以看到已经存在mysql.information_s ...

  3. prometheus 配置介绍

    prometheus 配置介绍 prometheus 配置分global.alerting.rule_files.scrape_configs 1.global(全局配置) scrape_interv ...

  4. 1.1浅谈Spring(一个叫春的框架)

    如今各种Spring框架甚嚣尘上,但是终归还是属于spring的东西.所以在这里,个人谈一谈对spring的认识,笔者觉得掌握spring原理以及spring所涉及到的设计模式对我们具有极大的帮助.我 ...

  5. CMDB服务器管理系统【s5day88】:采集资产-文件配置(二)

    上节疑问: 1.老师我们已经写到global_settings里了,为什么还要写到__init__.py setting 这的作用是为了:整合起两个的组合global_settings和setting ...

  6. 深入jar包:从jar包中读取资源文件getResourceAsStream

    一.背景 我们常常在代码中读取一些资源文件(比如图片,音乐,文本等等). 在单独运行的时候这些简单的处理当然不会有问题.但是,如果我们把代码打成一个jar包以后,即使将资源文件一并打包,这些东西也找不 ...

  7. Angular: 执行ng lint后如何快速修改错误

    当我第一次被分配到“修正执行ng lint语句后的错误”这项任务前,我就被导师提前告知这是一个很无聊的任务,当我开始后,我发现其实有一些办法可以加快这个无聊单调的工作.接下来,我就分享一下我的经验. ...

  8. IIS版本号可以被识别 解决方案

    1.在IIS配置文件中进行修改. 借助IIS URL Rewrite Module,添加如下的重写规则: <rewrite> <allowedServerVariables> ...

  9. DTO/DO等POJO对象的使用场景和 orika-mapper 框架的使用

    对于项目而言, 我们一般会有DAO->Service->Controller分层设计, 这些层次体现了每层的作用, 而层次之间的数据传递对象设计很少被提及, 下面是一个相对完整的数据转换过 ...

  10. python3中的socket

    socket是什么?用它做什么? socket,我们通俗的称之为套接字, 是进程间通信的一种方式,但是他与其他进程通信的一个主要区别是 他能实现不同主机间的通信,比如我们现在用的浏览器,在比如我们使用 ...