第01-100题
【Leetcode-easy-1】 Two Sum 两数之和
平生不识TwoSum,刷尽LeetCode也枉然
思路:
为了提高时间的复杂度,需要用空间来换,那么就是说只能遍历一个数字,那么另一个数字呢,我们可以事先将其存储起来,使用一个HashMap,来建立数字和其坐标位置之间的映射,我们都知道HashMap是常数级的查找效率,这样,我们在遍历数组的时候,用target减去遍历到的数字,就是另一个需要的数字了,直接在HashMap中查找其是否存在即可,注意要判断查找到的数字不是第一个数字,比如target是4,遍历到了一个2,那么另外一个2不能是之前那个2,整个实现步骤为:先遍历一遍数组,建立HashMap映射,然后再遍历一遍,开始查找,找到则记录index。
import java.util.*;
public class Solution {
/**
* You may assume that each input would have exactly one solution
*
* use Map
*/
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i ++){
int remainder = target - nums[i];
if(map.containsKey(nums[i]))
return new int[]{map.get(nums[i]), i};
map.put(remainder, i);
}
throw new IllegalArgumentException("no solution.");
}
}
【Leetcode-medium-2】 Add Two Numbers 两个数字相加
思路:建立一个新链表,然后把输入的两个链表从头往后撸,每两个相加,添加一个新节点到新链表后面,就是要处理下进位问题。还有就是最高位的进位问题要最后特殊处理一下。
/**
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
* 使用dummyHead避免写重复的代码,非常巧妙
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0); // 第二个结点是链表的头结点
int increment = 0;
ListNode currNode = dummyHead;
for (ListNode n1 = l1, n2 = l2; l1 != null || l2 != null;){
int x = l1 != null ? l1.val : 0;
int y = l2 != null ? l2.val : 0;
int result = x + y + increment;
currNode.next = new ListNode(result % 10);
increment = result / 10;
currNode = currNode.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (increment == 1){
currNode.next = new ListNode(1);
}
return dummyHead.next;
}
}
【Leetcode-medium-3】 Longest Substring Without Repeating Characters 最长无重复字符的子串
/**
* Given “abcabcbb”, the answer is “abc”, which the length is 3.
* Given “bbbbb”, the answer is “b”, with the length of 1.
*
*/
import java.util.*;
public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLen = 0;
StringBuilder sub = new StringBuilder(s.length());
int fromIndex = 0;
for (int i = 0; i < s.length(); i ++){
char ch = s.charAt(i);
int index = sub.indexOf(ch+"", fromIndex); // 重复“字符”(字符串)的位置
if (index != -1) fromIndex = index+1; // 不断调整起始下标
sub.append(ch);
int len = sub.length() - fromIndex; // 总长度 - 起始下标 = 当前子字符串的长度
if (maxLen < len) maxLen = len;
}
return maxLen;
}
}
【Leetcode-hard-4】
Median of Two Sorted Arrays 两个有序数组的中位数
思路:限制了时间复杂度为O(log (m+n)),应该使用二分查找法来求解。难点在于要在两个未合并的有序数组之间使用二分法,这里我们需要定义一个函数来找到第K个元素,由于两个数组长度之和的奇偶不确定,因此需要分情况来讨论,对于奇数的情况,直接找到最中间的数即可,偶数的话需要求最中间两个数的平均值。下面重点来看如何实现找到第K个元素,首先我们需要让数组1的长度小于或等于数组2的长度,那么我们只需判断如果数组1的长度大于数组2的长度的话,交换两个数组即可,然后我们要判断小的数组是否为空,为空的话,直接在另一个数组找第K个即可。还有一种情况是当K = 1时,表示我们要找第一个元素,只要比较两个数组的第一个元素,返回较小的那个即可。
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;
if (m < n) return findMedianSortedArrays(nums2, nums1);
if (n == 0) return (nums1[(m - 1) / 2] + nums1[m / 2]) / 2.0;
int left = 0, right = 2 * n;
while (left <= right) {
int mid2 = (left + right) / 2;
int mid1 = m + n - mid2;
double L1 = mid1 == 0 ? Double.MIN_VALUE : nums1[(mid1 - 1) / 2];
double L2 = mid2 == 0 ? Double.MIN_VALUE : nums2[(mid2 - 1) / 2];
double R1 = mid1 == m * 2 ? Double.MAX_VALUE : nums1[mid1 / 2];
double R2 = mid2 == n * 2 ? Double.MAX_VALUE : nums2[mid2 / 2];
if (L1 > R2) left = mid2 + 1;
else if (L2 > R1) right = mid2 - 1;
else return (Math.max(L1, L2) + Math.min(R1, R2)) / 2;
}
return -1;
}
}
【Leetcode-medium-5】 Longest Palindromic Substring 最长回文串
/**
* Input: “babad” Output: “bab”
* Input: “cbbd” Output: “bb”
*/
class Solution {
public String longestPalindrome(String s) {
int start = 0, end = 0;
for (int i = 0; i < s.length()-1; i ++){
int len1 = expandAroundCenter(s, i, i); // 假设回文字符串的长度是奇数
int len2 = expandAroundCenter(s, i, i+1); // 假设回文字符串的长度是偶数
int len = Math.max(len1, len2);
// 边界判断
if (len > end-start){
start = i - (len-1)/2; // 计算新的边界
end = i + len/2;
}
}
return s.substring(start, end+1);
}
// 从left,right向左右扩展
// 双参数真是很巧妙,一直卡在这里了
private int expandAroundCenter(String s, int left, int right){
int L = left, R = right;
for (; L >= 0 && R < s.length(); L --, R ++){
if (s.charAt(L) != s.charAt(R))
break;
}
return R-L-1; // 根据example判断是否减去1
}
}
【Leetcode-hard-10】 Regular Expression Matching 正则表达式匹配
Some examples:
isMatch(“aa”,”a”) → false
isMatch(“aa”,”aa”) → true
isMatch(“aaa”,”aa”) → false
isMatch(“aa”, “a*”) → true
isMatch(“aa”, “.*”) → true
isMatch(“ab”, “.*”) → true
isMatch(“aab”, “c*a*b”) → true思路:用递归Recursion来解,大概思路如下
若p为空,若s也为空,返回true,反之返回false
若p的长度为1,若s长度也为1,且相同或是p为’.’则返回true,反之返回false
若p的第二个字符不为*,若此时s为空返回false,否则判断首字符是否匹配,且从各自的第二个字符开始调用递归函数匹配
若p的第二个字符为*,若s不为空且字符匹配,调用递归函数匹配s和去掉前两个字符的p,若匹配返回true,否则s去掉首字母
返回调用递归函数匹配s和去掉前两个字符的p的结果
public class Solution {
public boolean isMatch(String s, String p) {
if(p.length() == 0)
return s.length() == 0;
//p's length 1 is special case
if(p.length() == 1 || p.charAt(1) != '*'){
if(s.length() < 1 || (p.charAt(0) != '.' && s.charAt(0) != p.charAt(0)))
return false;
return isMatch(s.substring(1), p.substring(1));
}else{
int len = s.length();
int i = -1;
while(i<len && (i < 0 || p.charAt(0) == '.' || p.charAt(0) == s.charAt(i))){
if(isMatch(s.substring(i+1), p.substring(2)))
return true;
i++;
}
return false;
}
}
}
【Leetcode-medium-11】 Container With Most Water 装最多水的容器
思路:
我们认为长度越长且高度越大,则面积越大。
现在,使用两个指针分别指向首、尾,这时它的宽度是最大的。
可能还会出现面积更大的情况,只有当高度变大的时候,所以可以移动两个指针中的较小者,这样可以能会使高度增加以弥补长度变短造成面积减少的损失。
一直移动两者中较小者,直到两者相遇,取各种情况的最大值即是最后的结果。
public int maxArea(int[] height){
int maxarea = 0;
int l = 0, r = height.length-1;
while(l < r){
int area = calArea(l, height[l], r, height[r]);
if (area > maxarea) maxarea = area;
if (height[l] <= height[r]) l ++;
else r --;
}
return maxarea;
}
private int calArea(int i, int h1, int j, int h2){
return Math.min(h1, h2) * (j-i);
}
【Leetcode-medium-15】 3Sum 三数之和
思路:
我们对原数组进行排序,然后开始遍历排序后的数组,这里注意不是遍历到最后一个停止,而是到倒数第三个就可以了。这里我们可以先做个剪枝优化,就是当遍历到正数的时候就break,为啥呢,因为我们的数组现在是有序的了,如果第一个要fix的数就是正数了,那么后面的数字就都是正数,就永远不会出现和为0的情况了。然后我们还要加上重复就跳过的处理,处理方法是从第二个数开始,如果和前面的数字相等,就跳过,因为我们不想把相同的数字fix两次。对于遍历到的数,用0减去这个fix的数得到一个target,然后只需要再之后找到两个数之和等于target即可。我们用两个指针分别指向fix数字之后开始的数组首尾两个数,如果两个数和正好为target,则将这两个数和fix的数一起存入结果中。然后就是跳过重复数字的步骤了,两个指针都需要检测重复数字。如果两数之和小于target,则我们将左边那个指针i右移一位,使得指向的数字增大一些。同理,如果两数之和大于target,则我们将右边那个指针j左移一位,使得指向的数字减小一些。
public List<List<Integer>> threeSum(int[] nums) {
ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums.length < 3) return result;
Arrays.sort(nums);
ArrayList<Integer> temp = null;
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; //选定nums[i]为第一个数,并去重
int left = i + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
temp = new ArrayList<Integer>();
temp.add(nums[i]);
temp.add(nums[left]);
temp.add(nums[right]);
result.add(temp);
while (left < right && nums[left] == nums[left + 1]) left++; //去重
while (left + 1 < right && nums[right] == nums[right - 1]) right--;
}
if (sum <= 0) left++;
else if (sum >= 0) right--;
}
}
return result;
}
【Leetcode-Easy-20】 Valid Parentheses 验证括号
思路:需要用一个栈,我们开始遍历输入字符串,如果当前字符为左半边括号时,则将其压入栈中,如果遇到右半边括号时,若此时栈为空,则直接返回false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回false
class Solution {
public boolean isValid(String s) {
LinkedList<String> stack = new LinkedList<>();
HashSet<String> set = new HashSet<>();
set.add("(");
set.add("[");
set.add("{");
for (int i = 0; i < s.length(); i ++){
String part = s.charAt(i) + "";
if (set.contains(part)) stack.push(part);
else{
if (stack.isEmpty()) return false;
String prepart = stack.pop();
if ("}".equals(part) && !"{".equals(prepart) ||
")".equals(part) && !"(".equals(prepart) ||
"]".equals(part) && !"[".equals(prepart)){
return false;
}
}
}
return stack.isEmpty();
}
}
//更为巧妙的解法
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == &