获得徽章 17
- #每日一题#
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n = nums1.length;
int m = nums2.length;
int left = (n + m + 1) / 2;
int right = (n + m + 2) / 2;
//将偶数和奇数的情况合并,如果是奇数,会求两次同样的 k 。
return (getKth(nums1, 0, n - 1, nums2, 0, m - 1, left) + getKth(nums1, 0, n - 1, nums2, 0, m - 1, right)) * 0.5;
}
private int getKth(int[] nums1, int start1, int end1, int[] nums2, int start2, int end2, int k) {
int len1 = end1 - start1 + 1;
int len2 = end2 - start2 + 1;
//让 len1 的长度小于 len2,这样就能保证如果有数组空了,一定是 len1
if (len1 > len2) return getKth(nums2, start2, end2, nums1, start1, end1, k);
if (len1 == 0) return nums2[start2 + k - 1];
if (k == 1) return Math.min(nums1[start1], nums2[start2]);
int i = start1 + Math.min(len1, k / 2) - 1;展开评论点赞 - #码上掘金# 给定一个字符串 s 和一个字符串数组 words。 words 中所有字符串 长度相同。
s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。
例如,如果 words = ["ab","cd","ef"], 那么 "abcdef", "abefcd","cdabef", "cdefab","efabcd", 和 "efcdab" 都是串联子串。 "acdbef" 不是串联子串,因为他不是任何 words 排列的连接。
返回所有串联字串在 s 中的开始索引。你可以以 任意顺序 返回答案。code.juejin.cn
展开赞过评论3 - #每日一题#
给定一个字符串 s 和一个字符串数组 words。 words 中所有字符串 长度相同。
s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。
例如,如果 words = ["ab","cd","ef"], 那么 "abcdef", "abefcd","cdabef", "cdefab","efabcd", 和 "efcdab" 都是串联子串。 "acdbef" 不是串联子串,因为他不是任何 words 排列的连接。
返回所有串联字串在 s 中的开始索引。你可以以 任意顺序 返回答案。
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> loc = new ArrayList<>();
int size = words[0].length();
for(int i = 0; i + size * words.length <= s.length(); i++){
List<String> wordList = new ArrayList<>();
Collections.addAll(wordList, words);
for(int j = i; j < i + size * words.length; j +=size){
String temp = s.substring(j, j + size);
if(!wordList.contains(temp)){
break;
}
wordList.remove(temp);
}
if(wordList.isEmpty()){
loc.add(i);
}
}
return loc;
}展开评论点赞 - #码上掘金# 给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。code.juejin.cn
展开赞过评论2 - #每日一题#
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
class Solution {
public int reverse(int x) {
long n = 0;
while (x != 0) {
n = x % 10 + n * 10;
x /= 10;
}
return (int)n == n ? (int)n : 0;
}
}展开评论点赞 - #每日一题# 实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)
class Solution {
public int myAtoi(String num) {
char[] chars = num.toCharArray();
int n = chars.length;
int ans = 0;
int index = 0;
boolean symbol = true;
while (index < n && num.charAt(index) == ' ') {
index++;
}
if (index == n) {
return 0;
}
if (num.charAt(index) == '-') {
symbol = false;
index ++;
} else if (num.charAt(index) == '+') {
index ++;
} else if (!Character.isDigit(num.charAt(index))) {
return 0;
}
while (index < n && Character.isDigit(num.charAt(index))) {
int digit = chars[index] - '0';
ans = ans * 10 + digit;
index ++;
}
return symbol ? ans : -1 * ans;
}
}展开评论点赞