leetcode medium
3 Longest Substring Without Repeating Characters
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.
思路1:O(n2)时间复杂度,尺取法,双指针枚举最长子串的开头和结尾,hash判断是否重
思路2:可针对1优化,若(i, j)不重复,而(i, j + 1)重复了(设重复的下标为m, j + 1),那么下一个最长子串只可能从(m + 1)开始,用map记住字符的下标即可。
#### 错误: 不能看到重复就新建map或仅更新该字符 ####
新建会丢失(m + 1, j)之间的信息。 仅更新该字符则会出现与(i ,m)之间重时认为不符合,其实符合 ====> 解决: 此时start 应 > map 取出的数,只在start小的时候更新即可。start = Math.max(start, m.get(s.charAt(end)));
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null) {
return 0;
}
int start = 0;
int end = 0;
int ans = 0;
Map<Character, Integer> m = new HashMap();
while (end < s.length()) {
if (m.containsKey(s.charAt(end))) {
//update the start
start = Math.max(start, m.get(s.charAt(end)));
}
ans = Math.max(ans, end - start + 1);
m.put(s.charAt(end), end + 1);
end++;
}
return ans;
}
}
5. Longest Palindromic Substring -- No
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is . Example: Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example: Input: "cbbd" Output: "bb"
枚举中间位置,O(n2).
或DP, 或转成求s与s的转置的lcs, 但注意特例abcadeabca这种情况。
class Solution {
public:
string longestPalindrome(string s) {
int start = ;
int maxlen = ;
int n = s.size();
for (int i = ; i < n; i++) {
int oddlen = expan(s, i, i);
int evenlen = expan(s, i, i+);
int len = max(oddlen, evenlen);
if (len > maxlen) {
start = i - (len-) / ;
maxlen = len;
}
}
return s.substr(start, maxlen);
}
private:
int expan(string s, int i, int j) {
int l = i;
int r = j;
int n = s.size();
while (l >= && r < n && s[l] == s[r]) {
l--;
r++;
}
return r-l-;
}
};
11. Container With Most Water -- No
given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, ). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least .
从一堆竖在二维平面的棍子中两根使与X轴组成的水杯容量最大。 两个指针往里缩即可。
1st: 看错题,以为是单调栈找面积。
class Solution {
public:
int maxArea(vector<int>& height) {
int l = ;
int r = height.size()-;
int maxarea = ;
while (l < r) {
int area = min(height[l], height[r]) * (r-l);
maxarea = max(area, maxarea);
if (height[l] < height[r]) {
l++;
} else {
r--;
}
}
return maxarea;
}
};
419. Battleships in a Board --No
iven an 2D board, count how many different battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
Example:
X..X
...X
...X
In the above board there are 2 battleships.
Invalid Example:
...X
XXXX
...X
This is an invalid board that you will not receive - as battleships will always have a cell separating between them.
Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
思路:在每个连续X的最后时 +1即可。
public class Solution {
public int countBattleships(char[][] board) {
if (board == null || board.length == 0) {
return 0;
}
int row = board.length;
int col = board[0].length;
int count = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (board[i][j] == '.') {
continue;
}
if (j > 0 && board[i][j - 1] == 'X') {
continue;
}
if (i >0 && board[i - 1][j] == 'X') {
continue;
}
count++;
}
}
return count;
}
}
658. Find K Closest Elements
Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred. Example :
Input: [,,,,], k=, x=
Output: [,,,]
Example :
Input: [,,,,], k=, x=-
Output: [,,,]
Note:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed
Absolute value of elements in the array and x will not exceed
思路:二分找到x在数组中的位置然后向两边扩展
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int index = std::lower_bound(arr.begin(), arr.end(), x) - arr.begin();
if (index == arr.size()) {
return vector<int> (arr.end()-k, arr.end());
}
if (index == ) {
return vector<int> (arr.begin(), arr.begin()+k);
}
int lo = max(index-k, );
int hi = min(index + k, (int)arr.size()-);
while (hi - lo > k-) {
if (abs(x-arr[lo]) > abs(x-arr[hi])) {
lo++;
} else {
hi--;
}
}
return vector<int> (arr.begin()+lo, arr.begin()+hi+);
}
};
leetcode medium的更多相关文章
- 每日温度(LeetCode Medium难度算法题)题解
LeetCode 题号739中等难度 每日温度 题目描述: 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数.如果之后都不会升高,请在该位置用 0 ...
- C# 写 LeetCode Medium #2 Add Two Numbers
2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. ...
- 黄金矿工(LeetCode Medium难度)1129题 题解(DFS)
题目描述: 给定一个二维网络,给定任意起点与终点.每一步可以往4个方向走.要找出黄金最多的一条线路. 很明显的是要“一条路走到黑,一直下去直到某个条件停止”. 运用dfs(深度优先搜索)求解. 因为起 ...
- 经验分享 | 如何拿到自己满意的offer?
本文阅读时间约16分钟 最近两年,人工智能(AI)就像一个点石成金的神器,所有的行业,创业公司,或是求职,只要沾着这个词,多少有点脚踩五彩祥云的感觉,故事来了,融资来了,高薪来了. 于是,越来越多的人 ...
- 三年半Java后端面试经历
经过半年的沉淀,加上对MySQL,redis和分布式这块的补齐,终于开始重拾面试信心,再次出征. 鹅厂 面试职位:go后端开发工程师,接受从Java转语言 都知道鹅厂是cpp的主战场,而以cpp为背景 ...
- AI面试刷题版
(1)代码题(leetcode类型),主要考察数据结构和基础算法,以及代码基本功 虽然这部分跟机器学习,深度学习关系不大,但也是面试的重中之重.基本每家公司的面试都问了大量的算法题和代码题,即使是商汤 ...
- [LeetCode] 034. Search for a Range (Medium) (C++/Java)
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 035. Sea ...
- [array] leetcode - 48. Rotate Image - Medium
leetcode - 48. Rotate Image - Medium descrition You are given an n x n 2D matrix representing an ima ...
- [array] leetcode - 40. Combination Sum II - Medium
leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...
随机推荐
- ASP.NET MVC 例子演示如何在 Knockout JS 的配合下,使用 TypeScript 。
一个简单的 ASP.NET MVC 例子演示如何在 Knockout JS 的配合下,使用 TypeScript . 前言 TypeScript 是一种由微软开发的自由和开源的编程语言.它是JavaS ...
- ASP.NET MVC显示WebForm网页或UserControl控件
ASP.NET MVC显示WebForm网页或UserControl控件 学习与使用ASP.NET MVC这样久,还是对asp.net念念不忘.能否在asp.net mvc去显示aspx或是user ...
- Ninject是一款.Net平台下的开源依赖注入框架
Ninject是一款.Net平台下的开源依赖注入框架.按照官方说法,它快如闪电.超级轻量,且充分利用了.Net的最新语法,使用Lambda表达式代替Xml文件完成类型绑定.Ninject结构精巧,功能 ...
- Moq的使用心得
Moq的使用心得 1.Moq中Mock Repository时最好是Mock Repository的接口,这样会避免不知名的错误. var mockClubRepository = new Mock& ...
- c/c++操作访问数据,是堆中的数据快还是栈中的数据快
这里的问题其实问的是对堆与栈的数据访问有什么不同. 观察如下代码: #include<stdio.h> #include<iostream> using namespace s ...
- net破解一(反编译,反混淆-剥壳,工具推荐)
net破解一(反编译,反混淆-剥壳,工具推荐) 大家好,前段时间做数据分析,需要解析对方数据,而数据文件是对方公司内部的生成方式,完全不知道它是怎么生成的. 不过还好能拿到客户端(正好是C#开发)所以 ...
- ssh配置公钥和私钥登陆SecureCRT
在用windows时管理linux服务器时,常会用到SecureCRT.Xshell以及开源的putty.在我工作环境大多都是采用密码认证的方式进行登录.今天对学习了些SecureCRT的密钥登录方式 ...
- C/C++基础知识总结——C++简单程序设计
1. sizeof 1.1 sizeof(类型名) 1.2 sizeof 表达式 1.3 返回所占字节大小 2. I/O流的输出格式 2.1 常用I/O流库操纵符 dec 十进制 he ...
- C#制作高仿360安全卫士窗体3
C#制作高仿360安全卫士窗体(三) 距上篇C#制作高仿360安全卫士窗体(二)也将近一个多月了,这个月事情还是像往常一样的多.不多我也乐在其中,毕竟我做的是我喜欢做的东西.今天特地抽空把怎么制作 ...
- Jquery文本框值改变事件(支持火狐、ie)
Jquery值改变事件支持火狐和ie浏览器,并且测试通过,绑定后台代码可以做成autocomplete控件. 具体代码列举如下: $(document).ready(function () { $(& ...