Question :301 - 400
# Question :301 - 400
# Q344: 反转字符串 (opens new window)
public void reverseString(char[] s) {
for (int i = 0, j = s.length - 1; i < j; i++, j--) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
# Q350: 两个数组的交集 II (opens new window)
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int len1 = nums1.length, len2 = nums2.length;
int i = 0, j = 0, c = 0;
int[] result = new int[Math.max(len1, len2)];
while (i < len1 && j < len2) {
if (nums1[i] == nums2[j]) {
result[c++] = nums1[i];
++i;
++j;
} else if (nums1[i] > nums2[j]) {
++j;
} else {
++i;
}
}
return c > 0 ? Arrays.copyOf(result, c) : new int[0];
}
# Q387: 字符串中的第一个唯一字符 (opens new window)
public int firstUniqChar(String s) {
int result = s.length();
for(char c = 'a'; c <= 'z'; c++) {
int index = s.indexOf(c);
if(index != -1 && index == s.lastIndexOf(c)) {
result = Math.min(result, index);
}
}
return result == s.length() ? -1 : result;
}
上次更新: 5/21/2023, 11:34:33 PM