11 Container With Most Water Medium
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, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
思路:先让底边最长,然后以当前情况下较高的那条边为基准去试底边变短的情况,是否可能面积变大。从两头向中间移动,遍历一遍即可,复杂度O(n)。
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {
i = 0;
j = height.length-1;
max_area = Number.MIN_VALUE;
while(i<j) {
area = Math.min(height[i],height[j])*(j-i);
if(area > max_area) {
max_area = area;
}
if(height[i] < height[j]) {
i++;
} else {
j--;
}
}
return max_area;
};
3 Longest Substring Without Repeating Characters Medium
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.
思路:指针j从左往右扫描,当遇到重复字母时,计算先前这段无重复子串的长度,找到这个子串中与指针j指向的字符重复的字符所在的index,以index+1作为新的搜索起始位置。遍历一遍即可,复杂度O(n)。
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length() == 0) {
return 0;
}
if(s.length() == 1) {
return 1;
}
int maxLength = 0;
int start = 0;
int j=1;
while(j<s.length()) {
String curStr = s.substring(0,j);
int index = curStr.indexOf(s.charAt(j),start);
if(index == -1) {
j++;
} else {
int len = j-start;
if(len > maxLength) {
maxLength = len;
}
start = index+1;
if(start >= s.length()) {
break;
}
j++;
}
}
if(j == s.length()) {
int len = j-start;
if(len > maxLength) {
maxLength = len;
}
}
return maxLength;
}
}