1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length < 2) return new int[]{-1, -1};
int[] res = {-1, -1};
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
res[0] = map.get(target - nums[i]);
res[1] = i;
}
map.put(nums[i], i);
}
return res;
}
}
2.两数相加
/*
两个链表对应节点相加,得到第三个链表
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res = new ListNode(0);
ListNode p = l1, q = l2;
ListNode cur = res;
int sum = 0;
while (p != null || q != null) {
if (p != null) {
sum += p.val;
p = p.next;
}
if (q != null) {
sum += q.val;
q = q.next;
}
cur.next = new ListNode(sum % 10);
sum /= 10;
cur = cur.next;
}
//最后一位进1
if (sum == 1) cur.next = new ListNode(1);
return res.next;
}
3.最大不重复子串长度
/**
* 滑动窗口最大长度
* @param s
* @return
*/
public int lengthOfLongestSubstring2(String s) {
if (s == null || s.length() == 0) return 0;
int maxlen = 0;
Map<Character, Integer> indexMap = new HashMap<>();
for (int i = 0, left = 0; i < s.length(); i++) {
if (indexMap.containsKey(s.charAt(i))) {
left = Math.max(left, indexMap.get(s.charAt(i)) + 1);
}
indexMap.put(s.charAt(i), i);
maxlen = Math.max(maxlen, i - left + 1);
}
return maxlen;
}
4. 两个有序数组的中位数
class Solution {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums;
int m = nums1.length;
int n = nums2.length;
nums = new int[m + n];
if (m == 0) {
if (n % 2 == 0) {
return (nums2[n / 2 - 1] + nums2[n / 2]) / 2.0;
} else {
return nums2[n / 2];
}
}
if (n == 0) {
if (m % 2 == 0) {
return (nums1[m / 2 - 1] + nums1[m / 2]) / 2.0;
} else {
return nums1[m / 2];
}
}
int count = 0;
int i = 0, j = 0;
while (count != (m + n)) {
if (i == m) {
while (j != n) {
nums[count++] = nums2[j++];
}
break;
}
if (j == n) {
while (i != m) {
nums[count++] = nums1[i++];
}
break;
}
if (nums1[i] < nums2[j]) {
nums[count++] = nums1[i++];
} else {
nums[count++] = nums2[j++];
}
}
if (count % 2 == 0) {
return (nums[count / 2 - 1] + nums[count / 2]) / 2.0;
} else {
return nums[count / 2];
}
}
}
5.最长回文子串
public String longestPalindrome(String s) {
int len = s.length();
if(s == null||len==0)return "";
boolean dp[][] = new boolean[len][len];
int max = 1;
String res = s.substring(0,1);
for(int i = 0;i<len;i++){
for(int j = 0;j<i;j++){
//j~i长度小于等于3或者j+1~i-1是回文
if(s.charAt(i)==s.charAt(j)&&((i-j<=2)||dp[j+1][i-1])){
dp[j][i]=true;
if(i-j+1>max){
max = i-j+1;
res = s.substring(j,i+1);
}
}
}
}
return res;
}
6.盛水最多的容器
class Solution {
public int maxArea(int[] height) {
if(height.length <= 1)return 0;
int res = 0;
int l = 0, r = height.length - 1;
while(l < r){
res = Math.max(res,(r-l)*Math.min(height[l],height[r]));
if(height[l]<height[r])l++;
else r--;
}
return res;
}
}