关于我的 Leetcode 题目解答,代码前往 Github:https://github.com/chenxiangcyr/leetcode-answers
LeetCode题目:228. Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
class Solution {
public List summaryRanges(int[] nums) {
List summary = new ArrayList<>();
int left = 0;
for (int i = 0; i < nums.length; i++) {
if (i + 1 < nums.length && nums[i + 1] == nums[i] + 1) {
continue;
}
if (left == i) {
summary.add(nums[left] + "");
}
else {
summary.add(nums[left] + "->" + nums[i]);
}
left = i + 1;
}
return summary;
}
}
LeetCode题目:163. Missing Ranges
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
For example, given [0, 1, 3, 50, 75]
, lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]
.
class Solution {
public List findMissingRanges(int[] nums, int lower, int upper) {
List list = new ArrayList();
if(nums == null) return list;
int n = nums.length;
for(int i = 0; i <= n; i++) {
long lt = (i == 0) ? lower : (long)nums[i - 1] + 1;
long gt = (i == n) ? upper : (long)nums[i] - 1;
addRange(list, lt, gt);
}
return list;
}
private void addRange(List list, long lo, long hi) {
if(lo > hi) return;
else if(lo == hi) list.add(String.valueOf(lo));
else list.add(lo + "->" + hi);
}
}
LeetCode题目:4. Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
思路参考 https://leetcode.com/articles/median-of-two-sorted-arrays/
class Solution {
public double findMedianSortedArrays(int[] A, int[] B) {
int m = A.length;
int n = B.length;
// 确保数组A长度小于等于数组B长度m <= n,因此确保 j 不会为负数
if (m > n) {
int[] temp = A;
A = B;
B = temp;
int tmp = m;
m = n;
n = tmp;
}
int iMin = 0;
int iMax = m;
int halfLen = (m + n + 1) / 2;
while (iMin <= iMax) {
// 初始从数组A的中间分隔
int i = (iMin + iMax) / 2;
// 确保条件1:`i + j == m + n - i - j`
int j = halfLen - i;
// i 太小,j 太大
if (i < iMax && B[j-1] > A[i]) {
iMin = iMin + 1;
}
// i 太大,j 太小
else if (i > iMin && A[i-1] > B[j]) {
iMax = iMax - 1;
}
// 确保条件2:`A[i - i] <= B[j] && B[j - 1] <= A[i]`
else {
// 找到左边集合最大的数
int maxLeft = 0;
if (i == 0) {
maxLeft = B[j-1];
}
else if (j == 0) {
maxLeft = A[i-1];
}
else {
maxLeft = Math.max(A[i-1], B[j-1]);
}
// 总共有奇数个数字,直接返回中间的数字
if ( (m + n) % 2 == 1 ) {
return maxLeft;
}
// 找到右边集合最小的数
int minRight = 0;
if (i == m) {
minRight = B[j];
}
else if (j == n) {
minRight = A[i];
}
else {
minRight = Math.min(B[j], A[i]);
}
// 总共有偶数个数字,返回中间的数字的平均数
return (maxLeft + minRight) / 2.0;
}
}
return 0.0;
}
}