下面为解题代码
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer,Integer> map=new HashMap<>(); for(int i=0;i<nums.length;i++){ int key=target-nums[i]; if(map.containsKey(key)){ return new int[]{i,map.get(key)}; }else{ map.put(nums[i],i); } } return new int[]{}; } }下面为解题代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy=new ListNode(0); ListNode currNode=dummy; int addNum=0; while (l1!=null||l2!=null){ int num=addNum; if(l1!=null){ num+=l1.val; l1=l1.next; } if(l2!=null){ num+=l2.val; l2=l2.next; } currNode.next=new ListNode(num%10); addNum=num/10; currNode=currNode.next; } if(addNum>0){ currNode.next=new ListNode(addNum); } return dummy.next; } }下面为解题代码
class Solution { public int lengthOfLongestSubstring(String s) { char[] chars = s.toCharArray(); int maxLen = 0; List<Character> list = new ArrayList<>(); for (char c : chars) { while (list.contains(c)) { list.remove(0); } list.add(c); if (list.size() > maxLen) { maxLen = list.size(); } } return maxLen; } }下面为解题代码
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { List<Integer> list = new ArrayList<>(); for (int i : nums1) { list.add(i); } for (int i : nums2) { list.add(i); } list.sort(Comparator.comparingInt(o -> o)); int size = list.size(); if (size < 2) { return (double) list.get(0); } if (size % 2 == 0) { return ((double) list.get(size / 2 - 1) + list.get(size / 2)) / 2; } return (double) list.get(size / 2); } } 解题思路2: 归并的思路但不new数组。 从两个数组分别取数。 先获得两个数组的长度和总长度 定义val1,val2,mIndex,nIndex 循环总长度一半+1,获得一半中的最大两个数 假如总长度为单数,返回val1和val2的max 否则返回两个值相加除二下面为解题代码
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int mLength = nums1.length; int nLength = nums2.length; int totalLength = nums1.length + nums2.length; int val1 = 0, val2 = 0, mIndex = 0, nIndex = 0; while (mIndex + nIndex < totalLength / 2 + 1) { val1 = val2; if (nIndex == nLength) { val2 = nums1[mIndex++]; continue; } if (mIndex == mLength || nums1[mIndex] >= nums2[nIndex]) { val2 = nums2[nIndex++]; } else { val2 = nums1[mIndex++]; } } if (totalLength % 2 == 0) { return (double)(val1 + val2) / 2; } return Math.max(val1, val2); } }输出:“bab” 解释:“aba” 同样是符合题意的答案。
输出:“bb”
输出:“a”
输出:“a”
s 仅由数字和英文字母(大写和/或小写)组成
👍 3120 👎 0
未完待续…
