文章目录
- LeetCode前100题目不同解法尝试
- 视频地址
- 1.Two Sum 两数之和
- 2. three Sum 三数之和
- 3.Longest SubString without Repeating Characters 最长无重复子串
- 3.Median of Two Sorted Arrays 寻找两个有序数组中位数
- 4.Median of two Sorted Arrays 寻找两个正序数组的中位数
- 5. Longest Palindromic Substring 最长回文子串
- 6. ZigZag Conversion Z字形变形
- 7. Reverse Integer 反转整数
- 8 String to Integer(atoi)
- 9. Palindrome Number 回文数
- 10.Container With most Water 盛水最多的容器
- 11.Roman to Integer 罗马数字转换为整数
- 12.Integer to Roman 整形转换为罗马数字
- 13Letters Combinations of Phone Number (电话号码数字组合)
- 14Longest Prefix 最长前缀
- 15.4Sum 四数之和
- 16 括号生成 Generate Parentheses
- 17 删除数组中重复的元素
- 18 Find the Index of the First Occurrence in a String
- 19 Add binary
- 20 Plus One
- 21 sqrt(x) x的平方根
- 22 Merge Sorted Array 合并 两个有序的数组
- 23Next Permutation
- 24 Divide Two Integers
- 25. Symmetric Tree 对称树
- 26. Same Tree
- 27. Climbing Stairs
- 28Valid Sudou
- 29 add Strings
- 30 Multiply Strings
- 31 Majority Element
- 32. Best Time to Buy and Sell Stock
- 33.Maximum Depth of Binary Tree
- 34 Counting bits
- 35 Find all numbers Disappeared in an Array
- 36 Jump game
LeetCode前100题目不同解法尝试
视频地址
1.Two Sum 两数之和
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2022/12/31 10:23
*
*
**/
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static void main(String[] args) {
int[] nums ={2,7,11,15};
int target = 18;
int[] res = twoSum(nums, target);
print(res);
}
static void print(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length && nums[i] + nums[j] == target; j++) {
res[0] = i;
res[1] = j;
}
}
return res;
}
public static int[] twoSum1(int[] nums, int target) {
int[] res = new int[2];
Map<Integer, Integer> map = new HashMap<>(16);
for (int i = 0; i < nums.length; i++) {
if(map.containsKey(target - nums[i])){
res[0] = map.get(target - nums[i]);
res[1] = i;
return res;
}
map.put(nums[i],i);
}
return res;
}
}
2. three Sum 三数之和
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2022/12/31 12:42
*
*
**/
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
//nums = [-1,0,1,2,-1,-4]
public class ThreeSum {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if(i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1,r = nums.length - 1;
while (l < r){
if( nums[i] + nums[l] + nums[r] == 0){
list.add(Arrays.asList(nums[i],nums[l],nums[r]));
l++;
r--;
while (l < r && nums[l] == nums[l + 1]) l++;
while (l < r && nums[r] == nums[r - 1]) r --;
}else if(nums[i] + nums[l] + nums[r] < 0){
//由于已经排好顺序,所以左边的数往左越来越大
l++;
}else {
r--;
}
}
}
return list;
}
public static void main(String[] args) {
int[] nums = {-1,0,1,2,-1,-4};
List<List<Integer>> lists = threeSum(nums);
for (List<Integer> list : lists) {
System.out.print(list + " ");
}
}
}
3.Longest SubString without Repeating Characters 最长无重复子串
package com.hou.monkey.leetcode;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class LongestNoRepeatSubString {
public static int lengthOfLongestSubstring(String s) {
// 记录字符上一次出现的位置
int[] last = new int[128];
// for(int i = 0; i < 128; i++) {
// last[i] = -1;
// }
int n = s.length();
int res = 0;
int start = 0; // 窗口开始位置
for(int i = 0; i < n; i++) {
int index = s.charAt(i);
// abcabcbb
// 97 start = 0,last[97] + 1 = 1
// res = Max.max(0, 0 - 1 + 1) = 0;
//last[97] = 0
// 98 start = 0,last[98] + 1 = 1
//res = Math.max(0,1 - 1 + 1) = 1
//last[98] = 1;
// 99 start = 0,last[99] + 1 = 1
//res = Math.max(0,2 - 1 + 1) = 2
//last[99] = 1;
// 97 start = 0,last[97] + 1 = 1
// res = Max.max(0, 3 - 1 + 1) = 3;
//last[97] = 3;
start = Math.max(start, last[index] + 1);
res = Math.max(res, i - start + 1);
last[index] = i;
}
return res;
}
public static int lengthOfLongestSubString1(String s){
//用来存储最长子串
Set<Character> sets = new HashSet<>();
//使用双指针解决这个问题
int rk = -1; //右指针
int res = 0;
for(int i = 0;i < s.length(); i ++){
if( i != 0){
sets.remove(s.charAt(i - 1));
}
while (rk + 1 < s.length() && !sets.contains(s.charAt( rk + 1))){
sets.add(s.charAt(rk + 1));
System.out.println("sets:"+sets);
rk ++;
}
res = Math.max(res,rk + 1 - i);
}
return res;
}
// abcabcaa
public static int longestLengthSubString4(String s){
int maxLen = 1;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j <s.length() ; j++) {
if(check(s,i,j)){
maxLen = Math.max(maxLen,j - i + 1);
}
}
}
return maxLen;
}
private static boolean check(String s, int start, int end) {
HashSet<Character> set = new HashSet<>();
for (int k = start; k <= end; k++) {
if(set.contains(s.charAt(k))){
return false;
}
set.add(s.charAt(k));
}
return true;
}
public static int lengthOfLongestSubstring5(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int max = 0, start = 0;
for (int end = 0; end < s.length(); end++) {
char ch = s.charAt(end);
if (map.containsKey(ch)){
//
start = Math.max(map.get(ch)+1,start);
}
max = Math.max(max,end - start + 1);
map.put(ch,end);
}
return max;
}
private static int longestLengthSubString1(String s) {
int l = 0,r = 0, maxLen = 0;
Set<Character> set = new HashSet<>();
while (r < s.length()){
while (set.contains(s.charAt(r))){
//左边移去,直到和右边没有一个重复的字符
set.remove(s.charAt(l));
l++;
}
set.add(s.charAt(s.charAt(r)));
maxLen = Math.max(maxLen,r - l + 1);
r++;
}
return maxLen;
}
public static void main(String[] args) {
String s = "pwwkew";
// System.out.println(lengthOfLongestSubstring(s));
// System.out.println(lengthOfLongestSubstring(s));
// System.out.println(lengthOfLongestSubString1(s));
System.out.println(longestLengthSubString4(s));
}
}
3.Median of Two Sorted Arrays 寻找两个有序数组中位数
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/4 10:04
*
*
**/
import java.util.Arrays;
public class MedianOfTwoSortedArrays {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] target = merge(nums1, nums2);
Arrays.sort(target);
double median = 0;
if(target.length % 2 == 0){
median = (target[target.length / 2] + target[target.length / 2 - 1]) / 2.0;
}else {
median = target[(target.length - 1) / 2];
}
// print(target);
//
System.out.println("median:" + median);
return median;
}
private static int[] merge(int[] nums1, int[] nums2) {
int[] num = new int[nums1.length + nums2.length];
/* System.arraycopy(nums1,0,num,0,nums1.length);
System.arraycopy(nums2,0,num,nums1.length,nums2.length);
*/
for (int i = 0; i < nums1.length; i++) {
num[i] = nums1[i];
}
for (int i = 0; i < nums2.length; i++) {
num[i + nums1.length] = nums2[i];
}
System.out.println(Arrays.toString(num));
return num;
}
public static void print(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int[] nums1 ={};
int[] nums2 = {3,4};
// findMedianSortedArrays(nums1,nums2);
double res = findMedianSortedArrays1(nums1,nums2);
System.out.println(res);
}
public static double findMedianSortedArrays1(int[] nums1,int[] nums2){
int m = nums1.length;
int n = nums2.length;
double median = 0;
if(m == 0){
if(n % 2 == 0){
return median = (nums2[n / 2 - 1] + nums2[n / 2]) / 2.0;
}else {
return median = nums2[n / 2];
}
}
if(n == 0){
if(m % 2 == 0){
return median = (nums1[n / 2 - 1] + nums1[n / 2]) / 2.0;
}else {
return median = nums1[n / 2];
}
}
int count = 0;
int i = 0;
int j = 0;
int[] nums = new int[m + n];
while (count !=(m + n)){
//这样加入的数组就是有序的
if(nums1[i] < nums2[j]){
nums[count++] = nums1[i++];
}else {
nums[count++] = nums2[j++];
}
if(i == m){
while (j != n){
nums[count++] = nums2[j++];
}
}else {
break;
}
if(j == n){
while (i != m){
nums[count++] = nums1[i++];
}
}else {
break;
}
}
if (count % 2 == 0){
return median = (nums[count / 2 - 1] + nums[count / 2] )/ 2.0;
}
return median = nums[count / 2];
}
}
4.Median of two Sorted Arrays 寻找两个正序数组的中位数
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/4 10:04
*
*
**/
import java.util.Arrays;
public class MedianOfTwoSortedArrays {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] target = merge(nums1, nums2);
Arrays.sort(target);
double median = 0;
if(target.length % 2 == 0){
median = (target[target.length / 2] + target[target.length / 2 - 1]) / 2.0;
}else {
median = target[(target.length - 1) / 2];
}
// print(target);
//
System.out.println("median:" + median);
return median;
}
private static int[] merge(int[] nums1, int[] nums2) {
int[] num = new int[nums1.length + nums2.length];
/* System.arraycopy(nums1,0,num,0,nums1.length);
System.arraycopy(nums2,0,num,nums1.length,nums2.length);
*/
for (int i = 0; i < nums1.length; i++) {
num[i] = nums1[i];
}
for (int i = 0; i < nums2.length; i++) {
num[i + nums1.length] = nums2[i];
}
System.out.println(Arrays.toString(num));
return num;
}
public static void print(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int[] nums1 ={};
int[] nums2 = {3,4};
// findMedianSortedArrays(nums1,nums2);
double res = findMedianSortedArrays1(nums1,nums2);
System.out.println(res);
}
public static double findMedianSortedArrays1(int[] nums1,int[] nums2){
int m = nums1.length;
int n = nums2.length;
double median = 0;
if(m == 0){
if(n % 2 == 0){
return median = (nums2[n / 2 - 1] + nums2[n / 2]) / 2.0;
}else {
return median = nums2[n / 2];
}
}
if(n == 0){
if(m % 2 == 0){
return median = (nums1[n / 2 - 1] + nums1[n / 2]) / 2.0;
}else {
return median = nums1[n / 2];
}
}
int count = 0;
int i = 0;
int j = 0;
int[] nums = new int[m + n];
while (count !=(m + n)){
//这样加入的数组就是有序的
if(nums1[i] < nums2[j]){
/*
* 相当于 nums[count] = nums1[i]; count++;i++;
* */
nums[count++] = nums1[i++];
}else {
nums[count++] = nums2[j++];
}
//两个for循环只执行一个
if(i == m){
while (j != n){
nums[count++] = nums2[j++];
}
//不可以用if --------else里面执行break,因为两个while循环一定会执行一个
break;
}
if(j == n){
while (i != m){
nums[count++] = nums1[i++];
}
}
}
if (count % 2 == 0){
return median = (nums[count / 2 - 1] + nums[count / 2] )/ 2.0;
}
return median = nums[count / 2];
}
}
5. Longest Palindromic Substring 最长回文子串
package com.hou.monkey.leetcode;
//最长回文子串的寻找
public class LongestPalindrome {
public static String logestPaildrome1(String s){
int maxLen = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
int currrentStrLen = 1;
int left = i - 1;
int right = i + 1;
while (left > 0 && s.charAt(left) == s.charAt(i)){
left--;
currrentStrLen++;
}
while (right < s.length() && s.charAt(right) == s.charAt(i)){
right++;
currrentStrLen++;
}
while (left > 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
left--;
right++;
currrentStrLen += 2;
}
if(maxLen < currrentStrLen){
maxLen = currrentStrLen;
start = left + 1;
}
}
return s.substring(start,start + maxLen);
}
public static void main(String[] args) {
String s = "acc";
String s1 = logestPaildrome1(s);
System.out.println(s1);
}
}
6. ZigZag Conversion Z字形变形
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/6 12:26
*
*
**/
public class ZigzagConversion {
public static void main(String[] args) {
String s = "PAYPALISHIRING";
// convert(s,3);
String s1 = convert1(s, 3);
System.out.println(s1);
/* String[] arrs = new String[3];
// arrs[0] = "goodjob";
for (int i = 0; i < arrs.length; i++) {
// if (arrs[i] != null && !"".equals(arrs[i])){
System.out.print(arrs[i]);
// }
}
*/
}
public static String convert1(String s, int numRows){
if(numRows == 1) return s;
String[] a = new String[numRows];
for (int i = 0; i < numRows;i++) {
a[i] = "";
}
char[] chars = s.toCharArray();
boolean flag = false;// true表示向下会自动 +1
for (int i = 0,row = 0; i < s.length(); i++) {
a[row] += s.charAt(i);
if(row == 0 || row == numRows - 1) flag = !flag;
row += flag == true ? 1 : -1;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < numRows; i++) {
builder.append(a[i]);
}
return builder.toString();
}
public static String convert2(String s, int numRows) {
String[] a = new String[numRows];
for(int i = 0; i < numRows;i++){
a[i] = "";
}
boolean flag = false;//表示向上的方向
for(int i = 0,row = 0; i < s.length();i++){
a[row] += s.charAt(i);
if(row == 0 || row == numRows - 1) flag = !flag;
row += flag ? 1 : -1;
}
String res = "";
for(int i = 0;i < numRows; i++){
res += a[i];
}
return res;
}
}
7. Reverse Integer 反转整数
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/11 10:19
*
*
**/
public class IntegerReverse {
public static String reverse(int x) {
if(x == 0) return String.valueOf(x);
char[] chars = String.valueOf(x).toCharArray();
StringBuilder stringBuilder = new StringBuilder();
if(x > 0){
for (int i = chars.length - 1; i >= 0; i--) {
if("0".equals(chars[chars.length - 1])){
if(!"0".equals(chars[i])){
stringBuilder.append(chars[i]);
}
}else {
stringBuilder.append(chars[i]);
}
}
}else {
for (int i = chars.length - 1; i > 0; i--) {
if("0".equals(chars[chars.length - 1])){
if(!"0".equals(chars[i])){
stringBuilder.append(chars[i]);
}
}else {
stringBuilder.append(chars[i]);
}
}
}
Math.abs(Integer.valueOf(String.valueOf(stringBuilder)));
if(x < 0) return String.valueOf("-" + stringBuilder );
System.out.println(Integer.valueOf(String.valueOf(stringBuilder)));
return String.valueOf(stringBuilder);
}
public static int reverse1(int x) {
int ans = 0;
// 求余在除
while (x != 0) {
//判断是否 大于 最大32位整数 官网给的判断是否在区间内
// if (ans < Integer.MIN_VALUE / 10 || ans > Integer.MAX_VALUE / 10) {
// return 0;
// }
ans = ans * 10 + x % 10;
//ans * 10 + x % 10 < Integer.MAX_VALUE;
// ans < Inetger.Max_VALUE / 10 - x % 10/10;
if (ans < Integer.MIN_VALUE || ans > Integer.MAX_VALUE / 10) {
return 0;
}
x /= 10;
}
System.out.println(ans);
return ans;
}
public static int reverse2(int x){
int ans = 0;
while (x != 0){
ans = ans * 10 + x % 10;
if(x > 0 && ans > (Integer.MAX_VALUE - x % 10) / 10) return 0;
if(x < 0 && ans < (Integer.MIN_VALUE- x % 10) / 10) return 0;
x /= 10;
}
return ans;
}
public static void main(String[] args) {
//reverse(1147483649);
reverse1(1147483648);
}
}
8 String to Integer(atoi)
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/12 11:44
*
*
**/
public class AtoiFunction {
public static int myAtoi(String s) {
//一个一个判断字符
char[] chars = s.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if(Character.isLetter(chars[0])){
return 0;
}
if(' '== chars[i]){
i++;
continue;
}
if('-' == chars[0] || '+' == chars[0]){
stringBuilder.append(chars[i]);
continue;
}
if(Character.isDigit(chars[i])){
stringBuilder.append(chars[i]);
}
}
if(Integer.valueOf(stringBuilder.toString()) > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(Integer.valueOf(stringBuilder.toString()) < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
return Integer.valueOf(stringBuilder.toString());
}
public static void main(String[] args) {
// System.out.println(myAtoi1("2147483648"));
System.out.println(myAtoi2(" 3453 5445 "));
}
public static int myAtoi1(String str){
int res = 0;
int i = 0;
int flag = 1;
if(i == str.length()) return 0;
str.trim();
/* while( i < str.length() && str.charAt(i) == ' '){
i++;
}*/
int start = i;
if( i < str.length() && start == i && str.charAt(i) == '-'){
flag = -1;
i++;
}
if( i < str.length() && start == i && str.charAt(i) == '+') {
flag = 1;
i++;
}
while (i < str.length() && Character.isDigit(str.charAt(i))){
int r = str.charAt(i) - '0';
/* if(res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE /10){
return flag > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}*/
if(res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE/10 && r>Integer.MAX_VALUE%10)){
return Integer.MAX_VALUE;
}
if(res < Integer.MIN_VALUE/10 || (res == Integer.MIN_VALUE/10 && -r<Integer.MIN_VALUE%10)){
return Integer.MIN_VALUE;
}
res = res * 10 + r;
i++;
}
return flag > 0 ? res : -res;
}
public static int myAtoi2(String s){
/* //if(s == null) return 0;
String s1 = s.trim();
//if(s == " ") return 0;
System.out.println("s:" + s);
System.out.println("s1:"+s1);*/
if(s == null) return 0;
s = s.trim();
if(s.isEmpty()) return 0;
int index = 0;
//定义是正数还是负数
int flag = 1;
char firstChar = s.charAt(index);
if(firstChar == '+'){
index++;
}
else if(firstChar == '-'){
index++;
flag = -1;
}
if(!Character.isDigit(firstChar)){
return 0;
}
int num = 0;
int res = num * flag;
while (index < s.length() && Character.isDigit(s.charAt(index))){
num = num * 10 + (s.charAt(index) - '0');
res = num * flag;
if(res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if(res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
index++;
}
return res;
}
}
9. Palindrome Number 回文数
class Solution {
public boolean isPalindrome(int x) {
if(x < 0) return false;
int num = x;
int cur = 0;
while(x != 0){
if(cur > Integer.MAX_VALUE / 10) return false;
cur = cur * 10 + x % 10;
x /= 10;
}
return num == cur;
}
public static boolean isPalindrome1(int x){
String s = String.valueOf(x);
StringBuilder stringBuilder = new StringBuilder(s);
System.out.println(stringBuilder);
System.out.println("反转之后的字符串:" + stringBuilder.reverse());
if(stringBuilder.equals(stringBuilder.reverse())){
return true;
}else {
return false;
}
}
}
10.Container With most Water 盛水最多的容器
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/14 16:10
*
*
**/
//盛水最多的容器
public class ContainerWithMostWater {
//
public static int maxArea(int[] height) {
int max = 0,ans = 0;
int l = 0;//左指针
int r = height.length - 1;
int min = 0;//用来存储最小的height
while (l < r){
ans = (r - l) * Math.min(height[l],height[r]);
max = max > ans ? max : ans;
if(height[l] <= height[r]){
l++;
}else {
r--;
}
/* l++; 找到了之后指针不是这样移动的
r--;*/
}
return max;
}
public static void main(String[] args) {
int[] arr = {1,8,6,2,5,4,8,3,7};
System.out.println(maxArea(arr));
}
}
11.Roman to Integer 罗马数字转换为整数
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/19 19:09
*
*
**/
public class RomanToInteger {
public static void main(String[] args) {
System.out.println(romanToInt("III"));
}
public static int romanToInt(String s) {
int sum = 0;
int preNum = getValue(s.charAt(0));
for(int i = 1;i < s.length();i++){
int num = getValue(s.charAt(i));
if(preNum >= num){
sum += preNum;
}else{
sum -= preNum;
}
preNum = num;
}
sum += preNum;
return sum;
}
private static int getValue(char ch) {
switch(ch) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
}
12.Integer to Roman 整形转换为罗马数字
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/18 12:44
*
*
**/
public class IntToRoman {
public String intToRoman(int num){
int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] response = {"M","CM","D","CD","C","L","XL","X","IX","V","IV","I"};
String res = "";
for (int i = 0; i < values.length; i++) {
while (num >= values[i]){
num -= values[i];
res += response[i];
}
}
return res;
}
public static int romanToInt(String s) {
if(s.equals("II")) return 2;
if(s.equals("III")) return 3;
int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] response = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int res = 0;
for(int i = 0;i< s.length();i++){
if(s.contains(response[i])){
res += values[i];
}
}
return res;
}
public static void main(String[] args) {
String res = "test";
String s = "CMXCIX";
System.out.println(romanToInt(s));
}
}
13Letters Combinations of Phone Number (电话号码数字组合)
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/22 16:25
*
*
**/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LetterCombinationsOfPhoneNumber {
public static List<String> letterCombinations(String digits) {
HashMap<Character, String> phoneMap = new HashMap<Character,String>(){{
put('2',"abc");
put('3',"def");
put('4',"ghi");
put('5',"jkl");
put('6',"mno");
put('7',"pqrs");
put('8',"tuv");
put('9',"wxyz");
}};
List<String> list = new ArrayList<>();
if (digits.length() == 0) return list;
StringBuilder sb = new StringBuilder();
backtrack(list,phoneMap,digits,0,sb);
return list;
}
private static void backtrack(List<String> list, HashMap<Character, String> phoneMap, String digits, int index, StringBuilder sb) {
if(index == digits.length()){
list.add(sb.toString());
}else {
char digit = digits.charAt(index);
String s = phoneMap.get(digit);
for (int i = 0; i < s.length(); i++) {
sb.append(s.charAt(i));
backtrack(list,phoneMap,digits,index + 1,sb);
sb.deleteCharAt(index);
}
}
}
public static void main(String[] args) {
System.out.println(letterCombinations("23"));
}
}
14Longest Prefix 最长前缀
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/20 12:00
*
*
**/
public class LongestCommonPrefix {
public static String longestCommonPrefix(String[] strs){
if(strs.length == 0) return "";
String ans = strs[0];
for (int i = 1; i < strs.length; i++) {
int j = 0;
for (;j < ans.length() && j < strs[i].length(); j++) {
if(ans.charAt(j) != strs[i].charAt(j)){
break;
}
}
ans = ans.substring(0,j);
if("".equals(ans)){
return ans;
}
}
return ans;
}
public static void main(String[] args) {
String[] strs = {"flower","ow","flight"};
System.out.println(longestCommonPrefix(strs));
}
}
15.4Sum 四数之和
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/1/26 19:38
*
*
**/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FourSum {
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
if (nums == null || nums.length < 4) {
return list;
}
int sum = 0;
for(int i = 0; i<nums.length -3;i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 3; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int l = j + 1, r = nums.length - 1;
while (l < r) {
sum = nums[i] + nums[j] + nums[l] + nums[r] - target;
if (sum == 0) {
list.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
while(l < r && nums[l] == nums[l++]) l++;
while(l < r && nums[r] == nums[r--]) r--;
l++;
r--;
} else if (sum > 0) {
r--;
} else {
l++;
}
}
}
}
return list;
}
public static void main(String[] args) {
int[] arr = {0,0,0,0};
System.out.println(fourSum(arr, 0));
}
}
16 括号生成 Generate Parentheses
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
dfs("",res,n,n);
return res;
}
public void dfs(String str,List<String> res,int l,int r){
if(l == 0 && r == 0){
res.add(str);
}
if(l > r ){
return;
}
if(l > 0){
dfs(str +"(",res,l - 1,r);
}
if(r > 0){
dfs(str + ")",res,l,r - 1);
}
}
}
17 删除数组中重复的元素
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length ;
int l = 1,r = 1;
while(r < n){
if(nums[r] != nums[r - 1]){
nums[l] = nums[r];
l++;
}
r++;
}
return l;
}
}
18 Find the Index of the First Occurrence in a String
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/2/9 13:47
*
*
**/
public class FindTheIndexOfTheFirstOccurrence {
public static int strStr(String haystack, String needle) {
if(!haystack.contains(needle)){
return -1;
}
for(int i = 0;i < haystack.length();i++){
if(haystack.substring(i,i + needle.length()).equals(needle)){
return i;
}
}
return -1;
}
public static int strStr1(String haystack, String needle) {
/* if(!haystack.contains(needle)){
return -1;
}*/
for(int i = 0;i < haystack.length() - needle.length() + 1;i++){
if(haystack.substring(i,i + needle.length()).equals(needle)){
return i;
}
}
return -1;
}
public static void main(String[] args) {
String haystack = "sadbutsad", needle = "but";
System.out.println(strStr(haystack, needle));
}
}
19 Add binary
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/2/11 10:22
*
*
**/
import java.math.BigInteger;
public class AddBinary {
public static String addBinary1(String a, String b) {
return new BigInteger(a, 2).add(new BigInteger(b, 2)).toString(2);
}
public static String addBinary2(String a, String b) {
StringBuilder builder = new StringBuilder();
int carry = 0;
for(int i = a.length() - 1,j = b.length() - 1;i >= 0 || j >= 0;i--,j--){
//进位进行下一次的求和操作
int sum = carry;
sum += i >= 0 ? a.charAt(i) - '0': 0;
sum += j >= 0 ? b.charAt(j) - '0' : 0;
builder.append(sum % 2);
//求进位,进位之后需要进行下一次的求和操作
carry = sum / 2;
}
//放入最后一次进位
builder.append(carry == 1 ? carry :"");
return builder.reverse().toString();
}
public static void main(String[] args) {
String a = "1010", b = "1011";
char c = '1' , d = '2';
int f = c - '0';
System.out.println(f);
//System.out.println(addBinary(a, b));
}
}
20 Plus One
class Solution {
public int[] plusOne(int[] digits) {
for(int i = digits.length - 1;i >= 0; i--){
if(digits[i] < 9){
// 23 不会进位的情况
digits[i]++;
return digits;
}else{
//进位的情况
digits[i] = 0;
}
}
//全部都会进位 99 + 1
digits = new int[digits.length + 1];
digits[0] = 1;
return digits;
}
}
21 sqrt(x) x的平方根
class Solution {
public int mySqrt(int x) {
int l = 0, r = x, ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if ((long) mid * mid <= x) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
public int mySqrt1(int x) {
for(int i = 0;i < x / 2 + 1;i++){
if(i*i <= x && (long)(i + 1) * (i + 1) > x){
return i;
}
}
return 0;
}
}
22 Merge Sorted Array 合并 两个有序的数组
int i = m - 1,j = n -1,k = m + n - 1;
while(i >= 0 && j >= 0){
if(nums1[i] > nums2[j]){
nums1[k--] = nums1[i--];
}else{
nums1[k--] = nums2[j--];
}
}
//剩余一个数组元素没有放入
while(i >= 0){
nums1[k--] = nums1[i--];
}
while(j >= 0){
nums1[k--] = nums2[j--];
}
23Next Permutation
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/2/15 10:44
*
*
**/
import java.util.Arrays;
public class NextPermutation {
public static void main(String[] args) {
int[] nums = {5,4,3,2,1};
//可以根据索引进行排序
Arrays.sort(nums,1,5);
print(nums);
}
public void nextPermutation(int[] nums) {
int n = nums.length;
for(int i = n - 1;i >= 0;i--){
if(i == 0){
Arrays.sort(nums);
return;
}else{
if(nums[i] > nums[i - 1]){
Arrays.sort(nums,i,n);
for(int j = i;j < n;j++) {
if(nums[j] > nums[i - 1]){
int temp = nums[i - 1];
nums[i - 1] = nums[j];
nums[j] = temp;
return;
}
}
}
}
}
}
public void nextPermutation1(int[] nums) {
int i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = nums.length - 1;
while (j >= 0 && nums[i] >= nums[j]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1);
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public void reverse(int[] nums, int start) {
int left = start, right = nums.length - 1;
while (left < right) {
swap(nums, left, right);
left++;
right--;
}
}
private static void print(int[] nums){
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
}
}
24 Divide Two Integers
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/2/15 10:44
*
*
**/
import java.util.Arrays;
public class NextPermutation {
public static void main(String[] args) {
int[] nums = {5,4,3,2,1};
//可以根据索引进行排序
Arrays.sort(nums,1,5);
print(nums);
}
public void nextPermutation(int[] nums) {
int n = nums.length;
for(int i = n - 1;i >= 0;i--){
if(i == 0){
Arrays.sort(nums);
return;
}else{
if(nums[i] > nums[i - 1]){
Arrays.sort(nums,i,n);
for(int j = i;j < n;j++) {
if(nums[j] > nums[i - 1]){
int temp = nums[i - 1];
nums[i - 1] = nums[j];
nums[j] = temp;
return;
}
}
}
}
}
}
public void nextPermutation1(int[] nums) {
int i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = nums.length - 1;
while (j >= 0 && nums[i] >= nums[j]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1);
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public void reverse(int[] nums, int start) {
int left = start, right = nums.length - 1;
while (left < right) {
swap(nums, left, right);
left++;
right--;
}
}
private static void print(int[] nums){
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
}
}
25. Symmetric Tree 对称树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root,root);
}
public boolean isMirror(TreeNode tree1,TreeNode tree2){
if(tree1 == null && tree2 == null) return true;
if(tree1 == null || tree2 == null) return false;
return (tree1.val == tree2.val)
&& isMirror(tree1.left,tree2.right)
&& isMirror(tree1.right,tree2.left);
}
}
26. Same Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null){
return true;
}
if(p == null || q == null){
return false;
}
if(p.val != q.val){
return false;
}
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}
27. Climbing Stairs
class Solution {
public int climbStairs(int i) {
if(i < 3) return i;
int a = 1,b = 2, sum = 0;
for (int i1 = 3; i1 <= i; i1++) {
sum = a + b;
a = b;
b = sum;
}
return sum;
}
}
28Valid Sudou
package com.hou.monkey.leetcode;/*
**
*@author SmallMonkey
*@Date 2023/2/17 12:01
*
*
**/
public class ValidSudo {
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j] >= '0' && board[i][j] <= '9'){
if(!getEffective(i, j, board)){
return false;
}
}
}
}
return true;
}
public boolean getEffective(int i, int j, char[][] board){
// 验证一行
for(int k = 0; k < board[i].length; k++){
if(board[i][k] == board[i][j] && k != j){
return false;
}
}
// 验证一列
for(int k = 0; k < board.length; k++){
if(board[k][j] == board[i][j] && k != i){
return false;
}
}
// 验证当前 3 * 3 数组
int heng = (i / 3) * 3;
int zhong = (j / 3) * 3;
for(int k1 = heng; k1 < heng + 3; k1++){
for(int k2 = zhong; k2 < zhong + 3; k2++){
if((board[k1][k2] == board[i][j]) && (k1 != i && k2 != j)){
return false;
}
}
}
return true;
}
public boolean isValidSudoku1(char[][] board) {
int[][] rows = new int[9][9];//存储每一年出现数字的次数
int[][] cols = new int[9][9];//存储每一列数字出现的次数
int[][][] sub = new int[3][3][9]; //存储每个3元内数字出现的次数;
for(int i = 0;i < board.length;i++){
for(int j = 0;j < board[0].length;j++){
char ch = board[i][j];
if(ch != '.'){
int num = ch - '0' - 1; //减1 不影响判断相同数字出现的次数,防止数组越界
rows[i][num]++;
cols[j][num]++;
sub[i/3][j/3][num]++;
if(rows[i][num] > 1 || cols[j][num] > 1 || sub[i/3][j/3][num] > 1){
return false;
}
}
}
}
return true;
}
public static void main(String[] args) {
int[][] borad = {
{2,3,6},
{9,5},
{3,9},
{3,7,9},
};
char c = '9';
int i = c - '0';
System.out.println(i);
System.out.println(borad.length);
System.out.println(borad[1].length);
}
}
29 add Strings
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder builder = new StringBuilder();
//因为我们相加的时候是从个位数开始加 指针指在最后位置
int i = num1.length() - 1,j = num2.length() - 1,carry = 0;
while(i >= 0 || j >= 0 || carry != 0){
int sum = i >= 0 ? num1.charAt(i) - '0' : 0;
sum += j >= 0 ? num2.charAt(j) - '0' : 0;
int tmp = sum + carry;
builder.append(tmp % 10);
carry = tmp / 10;
i--;
j--;
}
//if(carry != 0) builder.append(carry);
return builder.reverse().toString();
}
}
30 Multiply Strings
class Solution {
public String multiply(String num1, String num2) {
if("0".equals(num1) || "0".equals(num2)){
return "0";
}
int n = num1.length(),m = num2.length();
//不用定义成char类型的数组,因为计算乘法的时候又需要转换成int类型,比较麻烦
int[] res = new int[n + m];
// 1 2 3
// 4 5 6 18 i + j ===> 8 i + j + 1 == > 1
for(int i = n - 1;i >= 0;i--){
for(int j = m - 1;j >= 0;j--){
int ans = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int sum = res[i + j + 1] + ans;
res[i + j + 1] = sum % 10;
res[i + j] +=sum / 10;
}
}
StringBuilder builder = new StringBuilder();
for(int i : res){
if(i == 0 && builder.length() == 0 ) continue;
builder.append(i);
}
return builder.toString();
}
}
31 Majority Element
因为它出现的次数会大于 n/ 2;
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
32. Best Time to Buy and Sell Stock
class Solution {
public int maxProfit(int[] prices) {
// int res = 0;
// for(int i = 0;i < prices.length;i++){
// for(int j = i + 1;j < prices.length; j++){
// res = Math.max(prices[j] - prices[i],res);
// }
// }
// return res;
int minValue = Integer.MAX_VALUE;
int maxProfit = 0;
for(int i = 0;i < prices.length;i++){
if(prices[i] < minValue){
minValue = prices[i];
}else if(prices[i] - minValue > maxProfit){
maxProfit = prices[i] - minValue;
}
}
return maxProfit;
}
}
33.Maximum Depth of Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
//递归方法求解
//return 1 + Math.max(maxDepth(root.left),maxDepth(root.right));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int res = 0;
while(!queue.isEmpty()){
int size = queue.size();
while(size-- > 0){
TreeNode node = queue.poll();
if(node.left !=null){
queue.add(node.left);
}
if(node.right !=null){
queue.add(node.right);
}
}
//加了一层之后,res + 1
res++;
}
return res;
}
}
34 Counting bits
class Solution {
public int[] countBits(int n) {
// 0 1 2 3 4 5 6 110
int[] res = new int[n + 1];
for(int i = 0;i <= n;i++){
if(i % 2 == 0){
res[i] = res[i / 2];
}else{
res[i] = res[i / 2] + 1;
}
}
return res;
}
}
35 Find all numbers Disappeared in an Array
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
// int n = nums.length;
// int[] count =new int[n];
// List<Integer> res = new ArrayList<>();
// for(int i = 0;i < n;i++){
// //count the num[i] times count[num[i]] = cont[num[i]] + 1
// count[nums[i] - 1]++;
// }
// for(int i = 0;i < n;i++){
// if(count[i] == 0){
// res.add(i + 1);
// }
// }
// return res;
// follow up
int n = nums.length;
List<Integer> res = new ArrayList<>();
for(int i = 0;i < n;i++){
//nums the num[i] times count[num[i]] = cont[num[i]] + 1
// nums[i] - 1 just for don't out of index
int x = (nums[i] - 1) % n;
nums[x] += n;
}
for(int i = 0;i < n;i++){
if(nums[i] <= n){
// because the up substract 1,so this will add 1
res.add(i + 1);
}
}
return res;
}
}
36 Jump game
public class Solution {
public boolean canJump(int[] nums) {
// int n = nums.length;
// int rightMax = 0;
// for(int i = 0;i < n;++i){
// if(i <= rightMax){
// rightMax = Math.max(rightMax,i + nums[i]);
// if(rightMax >= n - 1){
// return true;
// }
// }
// }
// return false;
// int reach = 0,n = nums.length;
// for(int i = 0;i < n;++i){
// // 1 > 3
// if(i > reach){
// return false;
// }
// // 3
// reach = Math.max(i + nums[i],reach);
// }
// return true;
// 优化之后的answer
int reach = 0,n = nums.length;
for(int i = 0;i <= reach && reach < n -1;++i){
reach = Math.max(i + nums[i],reach);
}
return reach >= n - 1;
// int last = nums.length - 1,n = nums.length;
// for(int i = n - 2;i >= 0;i--){
// if(i + nums[i] >= last){
// last = i;
// }
// }
// return last == 0;
}
}