1. 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] numsCopy = nums.clone();
Arrays.sort(numsCopy);
int i = 0, j = nums.length - 1;
while (i < j) {
if (numsCopy[i] + numsCopy[j] == target) {
break;
} else if (numsCopy[i] + numsCopy[j] < target) {
i++;
} else {
j--;
}
}
int[] res = new int[]{-1,-1};
for (int k = 0; k < nums.length; k++) {
if (nums[k] == numsCopy[i] && res[0]==-1) {
res[0] = k;
} else if (nums[k] == numsCopy[j]) {
res[1] = k;
}
}
Arrays.sort(res);
return res;
}
}
2. 两数相加
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode cur1 = l1, cur2 = l2, cur3 = dummy;
int more = 0;
while(cur1 != null || cur2 != null || more > 0){
int sum = (cur1 == null? 0:cur1.val) + (cur2 == null? 0:cur2.val)+ more;
more = sum/10;
sum = sum%10;
cur3.next = new ListNode(sum);
cur3 = cur3.next;
if(cur1 != null){
cur1 = cur1.next;
}
if(cur2 != null){
cur2 = cur2.next;
}
}
return dummy.next;
}
}
3. 无重复字符的最长子串
class Solution {
public int lengthOfLongestSubstring(String s) {
int left = 0, right = 0;
int len = s.length();
HashSet<Character> set = new HashSet<>();
int maxlen = 0;
while(left < len && right < len){
if(!set.contains(s.charAt(right))){
set.add(s.charAt(right));
maxlen = Math.max(maxlen, right - left + 1);
right ++;
}else{
while(s.charAt(left)!=s.charAt(right)){
set.remove(s.charAt(left));
left ++;
}
set.remove(s.charAt(left));
left ++;
}
}
return maxlen;
}
}
5. 最长回文子串
class Solution {
public String longestPalindrome(String s) {
String result = "";
int maxlen = 0;
for(int i = 0;i<s.length();i++){
String temp = getSubString(s,i,i);
if(temp.length()>maxlen){
result = temp;
maxlen = temp.length();
}
temp = getSubString(s,i,i+1);
if(temp.length()>maxlen){
result = temp;
maxlen = temp.length();
}
}
return result;
}
public String getSubString(String s,int i,int j){
while(i >= 0 && j < s.length() && s.charAt(i)==s.charAt(j)){
i--;
j++;
}
return s.substring(i+1,j);
}
}
7. 整数反转
class Solution {
public int reverse(int x) {
String xstr = String.valueOf(x);
String result = "";
if (xstr.charAt(0) == '-') {
result = '-' + strReverse(xstr.substring(1, xstr.length()));
} else {
result = strReverse(xstr);
}
long longx = Long.parseLong(result);
if (longx > Math.pow(2, 31) - 1 || longx < -Math.pow(2, 31)) {
return 0;
}
// if (longx > Integer.MAX_VALUE || longx < Integer.MIN_VALUE) {
// return 0;
// }
return Integer.parseInt(result);
}
String strReverse(String xstr) {
int i = 0;
int j = xstr.length() - 1;
char[] chars = xstr.toCharArray();
while (i < j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
i++;
j--;
}
return new String(chars);
}
}
9. 回文数
class Solution {
public boolean isPalindrome(int x) {
String str = String.valueOf(x);
int i = 0 , j = str.length()-1;
while(i<j){
if(str.charAt(i) != str.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
}
11. 盛最多水的容器
class Solution {
public int maxArea(int[] height) {
int left= 0,right = height.length-1;
int maxArea = 0;
while(left <= right){
maxArea = Math.max(maxArea,(right-left)*Math.min(height[left],height[right]));
if(height[left]<height[right]){
left ++;
}else{
right--;
}
}
return maxArea;
}
}
15. 三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int n = nums.length;
if (n < 3) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < n - 2; i++) {
if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1, k = n - 1;
int target = -nums[i];
while (j < k) {
if (nums[j] + nums[k] < target) {
j++;
} else if (nums[j] + nums[k] > target) {
k--;
} else if (nums[j] + nums[k] == target) {
res.add(new ArrayList<>(Arrays.asList(nums[i], nums[j++], nums[k--])));
while (j < k && nums[j] == nums[j - 1]) j++;
while (j < k && nums[k] == nums[k + 1]) k--;
}
}
}
return res;
}
}
16. 最接近的三数之和
class Solution {
public int threeSumClosest(int[] nums, int target) {
int n = nums.length;
int best = 10000000;
Arrays.sort(nums);
for(int i = 0;i<n-2;i++){
int j = i+1,k=n-1;
while(j<k){
int sum = nums[i]+nums[j]+nums[k];
if(sum == target){
return sum;
}
if(Math.abs(sum-target)<Math.abs(best - target)){
best = sum;
}
if(sum > target){
k--;
}else if(sum<target){
j++;
}
}
}
return best;
}
}
17. 电话号码的字母组合
class Solution {
public List<String> letterCombinations(String digits) {
HashMap<Character,String> digitMap = new HashMap<>(){
{
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> res = new ArrayList<String>();
if(digits.length()==0){
return res;
}
LinkedList<Character> temp = new LinkedList<Character>();
backTrack(res,digits,0,temp,digitMap);
return res;
}
public void backTrack(List<String> res,String digits,int index,LinkedList<Character> temp,HashMap<Character,String> digitMap){
if(index == digits.length()){
res.add(temp.stream().map(String::valueOf).collect(Collectors.joining()));
return;
}
char key = digits.charAt(index);
String mapstr = digitMap.get(key);
for(char ch:mapstr.toCharArray()){
temp.add(ch);
backTrack(res,digits,index+1,temp,digitMap);
temp.removeLast();
}
}
}
//StringBuffer sb.deleteCharAt(index);
19. 删除链表的倒数第 N 个结点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pfast = dummy,pslow = dummy;
for(int i = 0;i<n;i++){
pfast = pfast.next;
}
while(pfast.next!=null){
pfast = pfast.next;
pslow = pslow.next;
}
pslow.next = pslow.next.next;
return dummy.next;
}
}
20. 有效的括号
class Solution {
public boolean isValid(String s) {
if(s == null || s.length() == 0 ) {
return false;
}
LinkedList<Character> stk = new LinkedList<Character>();
char[] chs = s.toCharArray();
for(char ch: chs){
if(ch == '('){
stk.addLast(')');
}
else if(ch == '['){
stk.addLast(']');
}else if(ch == '{'){
stk.addLast('}');
}
else if(!stk.isEmpty() && ch == stk.getLast()){
stk.removeLast();
}else{
return false;
}
}
return stk.isEmpty();
}
}
21. 合并两个有序链表
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode();
ListNode cur1 = list1,cur2 = list2,cur3 = dummy;
while(cur1 != null && cur2 != null){
if(cur1.val < cur2.val){
cur3.next = cur1;
cur1 = cur1.next;
}else{
cur3.next = cur2;
cur2 = cur2.next;
}
cur3 = cur3.next;
}
cur3.next = (cur1 == null)?cur2:cur1;
return dummy.next;
}
}
22. 括号生成
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
generateParenthesis(result,n,n,"");
return result;
}
public void generateParenthesis(List<String> result,int left,int right,String str){
if(left == 0 && right == 0){
result.add(str);
}
if(left > 0){
generateParenthesis(result,left-1,right,str+"(");
}
if(right > left){
generateParenthesis(result,left,right-1,str+")");
}
}
}
23. 合并K个升序链表
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) {
return null;
}
return mergeKLists(lists, 0, lists.length - 1);
}
public ListNode mergeKLists(ListNode[] lists, int left, int right) {
if (left == right) {
return lists[left];
}
int mid = (left + right) / 2;
return mergeTwoLists(mergeKLists(lists, left, mid), mergeKLists(lists, mid + 1, right));
}
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode();
ListNode cur1 = list1, cur2 = list2, cur3 = dummy;
while (cur1 != null && cur2 != null) {
if (cur1.val < cur2.val) {
cur3.next = cur1;
cur1 = cur1.next;
} else {
cur3.next = cur2;
cur2 = cur2.next;
}
cur3 = cur3.next;
}
cur3.next = (cur1 == null) ? cur2 : cur1;
return dummy.next;
}
}
24. 两两交换链表中的节点
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode temp = dummy;
while(temp.next!=null && temp.next.next!=null){
ListNode node1 = temp.next;
ListNode node2 = temp.next.next;
temp.next = node1.next;
node1.next = node2.next;
node2.next = node1;
temp = node1;
}
return dummy.next;
}
// 递归
public ListNode swapPairs2(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode newhead = head.next;
head.next = swapPairs(newhead.next);
newhead.next = head;
return newhead;
}
}
25. K 个一组翻转链表
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null){
return head;
}
ListNode tail = head;
for(int i = 0;i<k;i++){
if(tail == null){
return head;
}
tail = tail.next;
}
ListNode newhead = reverse(head,tail);
head.next = reverseKGroup(tail,k);
return newhead;
}
public ListNode reverse(ListNode head,ListNode tail){
ListNode pre = null;
while(head != tail){
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}
27. 移除元素
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
for(int j = 0;j<nums.length;j++){
if(nums[j]!=val){
nums[i++]=nums[j];
}
}
return i;
}
}
30. 串联所有单词的子串
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> res = new ArrayList<>();
if (s == null || s.length() == 0 || words == null || words.length == 0) return res;
int wordlen = words[0].length();
int wordnum = words.length;
Map<String, Integer> smap = new HashMap<>();
for (String word : words) {
smap.put(word, smap.getOrDefault(word, 0) + 1);
}
for (int i = 0; i < s.length() - wordlen * wordnum + 1; i++) {
Map<String, Integer> tmap = new HashMap<>();
for (int j = i; j < i + wordlen * wordnum; j += wordlen) {
String str = s.substring(j, j + wordlen);
tmap.put(str, tmap.getOrDefault(str, 0) + 1);
}
if (smap.equals(tmap)) res.add(i);
}
return res;
}
}
32. 最长有效括号
class Solution {
public int longestValidParentheses(String s) {
int ans = 0;
LinkedList<Integer> stk = new LinkedList<>();
stk.addLast(-1);
for(int i = 0;i<s.length();i++){
char ch = s.charAt(i);
if(ch == '('){
stk.addLast(i);
}else{
stk.removeLast();
if(stk.isEmpty()){
stk.add(i);
}else{
ans = Math.max(ans,i-stk.getLast());
}
}
}
return ans;
}
}
36. 有效的数独
class Solution {
public boolean isValidSudoku(char[][] board) {
int[][] rows = new int[9][9];
int[][] cols = new int[9][9];
int[][][] threes = new int[3][3][9];
for(int i = 0;i<9;i++){
for(int j = 0;j<9;j++){
if(board[i][j]=='.'){
continue;
}
int index = board[i][j]-'0'-1;
rows[i][index]++;
cols[index][j]++;
threes[i/3][j/3][index]++;
if(rows[i][index]>1 || cols[index][j]>1 || threes[i/3][j/3][index]>1){
return false;
}
}
}
return true;
}
}
37. 解数独
class Solution {
private boolean[][] line = new boolean[9][9];
private boolean[][] column = new boolean[9][9];
private boolean[][][] block = new boolean[3][3][9];
private boolean valid = false;
private List<int[]> spaces = new ArrayList<int[]>();
public void solveSudoku(char[][] board) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
spaces.add(new int[]{i, j});
} else {
int digit = board[i][j] - '0' - 1;
line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
}
}
}
dfs(board, 0);
}
public void dfs(char[][] board, int pos) {
if (pos == spaces.size()) {
valid = true;
return;
}
int[] space = spaces.get(pos);
int i = space[0], j = space[1];
for (int digit = 0; digit < 9 && !valid; ++digit) {
if (!line[i][digit] && !column[j][digit] && !block[i / 3][j / 3][digit]) {
line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
board[i][j] = (char) (digit + '0' + 1);
dfs(board, pos + 1);
line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = false;
}
}
}
}
38. 外观数列
class Solution {
public String countAndSay(int n) {
String str = "1";
for (int i = 2; i <= n; ++i) {
StringBuilder sb = new StringBuilder();
int start = 0;
int pos = 0;
while (pos < str.length()) {
while (pos < str.length() && str.charAt(pos) == str.charAt(start)) {
pos++;
}
sb.append(Integer.toString(pos - start)).append(str.charAt(start));
start = pos;
}
str = sb.toString();
}
return str;
}
}
39. 组合总和
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
//Arrays.sort(candidates);
combination(res, temp, 0, candidates, target);
return res;
}
public void combination(List<List<Integer>> res, List<Integer> temp, int begin, int[] candidates, int target) {
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<Integer>(temp));
return;
}
for (int i = begin; i < candidates.length; i++) {
temp.add(candidates[i]);
combination(res, temp, i, candidates, target - candidates[i]);
temp.remove(temp.size() - 1);
}
}
}
40. 组合总和 II
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
Arrays.sort(candidates);
combination(res, temp, 0, candidates, target);
return res;
}
public void combination(List<List<Integer>> res, List<Integer> temp, int begin, int[] candidates, int target) {
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<Integer>(temp));
return;
}
for (int i = begin; i < candidates.length; i++) {
if(i!=begin && candidates[i]==candidates[i-1])
continue;
temp.add(candidates[i]);
combination(res, temp, i+1, candidates, target - candidates[i]);
temp.remove(temp.size() - 1);
}
}
}
41. 缺失的第一个正数
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for(int i = 0;i<n;i++){
while(nums[i]>0 && nums[i]<=n && nums[i] != nums[nums[i] - 1]){
int temp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = temp;
}
}
for(int i=0;i<n;i++){
if(nums[i]!=i+1){
return i+1;
}
}
return n+1;
}
}
42. 接雨水
class Solution {
public int trap(int[] height) {
int len = height.length;
if(len <= 2){
return 0;
}
int maxLeft = height[0],maxRight = height[len-1];
int i = 0,j = len-1;
int res = 0;
while(i<j){
if(maxLeft < maxRight){
i++;
maxLeft = Math.max(maxLeft,height[i]);
res+=(maxLeft-height[i]);
}else{
j--;
maxRight = Math.max(maxRight,height[j]);
res+=(maxRight-height[j]);
}
}
return res;
}
}
46. 全排列
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
recursion(res, 0, nums);
return res;
}
public void recursion(List<List<Integer>> res, int begin, int[] nums) {
if (begin == nums.length) {
List<Integer> temp = new ArrayList<Integer>();
for (int num : nums) {
temp.add(num);
}
res.add(temp);
return;
}
for (int i = begin; i < nums.length; i++) {
swap(nums, begin, i);
recursion(res, begin + 1, nums);
swap(nums, begin, i);
}
}
private void swap(int[] nums, int i, int j) {
int a = nums[i];
nums[i] = nums[j];
nums[j] = a;
}
}
47. 全排列 II
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
recursion(res, 0, nums);
return res;
}
public void recursion(List<List<Integer>> res, int begin, int[] nums) {
if (begin == nums.length) {
List<Integer> temp = new ArrayList<Integer>();
for(int num:nums){
temp.add(num);
}
res.add(temp);
return;
}
for (int i = begin; i < nums.length; i++) {
Boolean isdup = false;
for (int j = begin; j < i; j++){
if (nums[j] == nums[i]){
isdup = true;
break;
}
}
if (isdup)
continue;
swap(nums,begin,i);
recursion(res, begin + 1, nums);
swap(nums,begin,i);
}
}
private void swap(int[] nums,int i,int j){
int a = nums[i];
nums[i] = nums[j];
nums[j]=a;
}
}
49. 字母异位词分组
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] strArray = str.toCharArray();
Arrays.sort(strArray);
String str1 = new String(strArray);
if (map.containsKey(str1)) {
map.get(str1).add(str);
} else {
List<String> strList = new ArrayList<>();
strList.add(str);
map.put(str1, strList);
}
}
for (List<String> aa : map.values()) {
res.add(aa);
}
return res;
}
}
53. 最大子数组和
class Solution {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int pre = nums[0];
for(int i = 1;i<nums.length;i++){
int num = nums[i];
if(pre >0){
num+=pre;
}
pre = num;
maxSum = Math.max(maxSum,num);
}
return maxSum;
}
}
61. 旋转链表
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null)
return head;
int len = 0;
ListNode cur = head, pre = null;
while (cur != null) {
pre = cur;
cur = cur.next;
len++;
}
pre.next = head;
k = k % len;
cur = head;
for (int i = 0; i < len - k-1; i++) {
cur = cur.next;
}
ListNode res = cur.next;
cur.next = null;
return res;
}
}
77. 组合
class Solution {
public List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
List<Integer> temp = new ArrayList<Integer>();
recursion(temp,1,k,n);
return result;
}
public void recursion(List<Integer> temp,int index,int k,int n){
if(k == 0){
result.add(new ArrayList<Integer>(temp));
return;
}
for(int i = index;i<=n;i++){
temp.add(i);
recursion(temp,i+1,k-1,n);
temp.remove(temp.size()-1);
}
}
}