提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
如果想把这道题目做到极致,就不要只用额外的辅助空间了! (不过使用Java刷题的录友,一定要使用辅助空间,因为Java里的string不能修改)
一、力扣18. 四数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
int n = nums.length;
if(n < 4){
return res;
}
Arrays.sort(nums);
for(int i = 0; i < n-3; i ++){
if(nums[i] > 0 && target < 0){
continue;
}
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
for(int j = i+1; j < n-2; j ++){
if(j > i+1 && nums[j] == nums[j-1]){
continue;
}
int left = j+1, right = n-1;
while(left < right){
if(left > j+1 && nums[left] == nums[left-1]){
left ++;
continue;
}
if(right < n-1 && nums[right] == nums[right+1]){
right --;
continue;
}
int temp = nums[i] + nums[j] + nums[left] + nums[right];
if(temp == target){
res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
left ++;
right --;
}else if(temp > target){
right --;
}else{
left ++;
}
}
}
}
return res;
}
}
二、力扣344. 反转字符串
class Solution {
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;
}
}
}
三、力扣541. 反转字符串 II
class Solution {
public String reverseStr(String s, int k) {
char[] ch = s.toCharArray();
for(int i = 0; i < ch.length; i += 2*k){
if(i+k-1 <= ch.length-1){
ch = fun(ch,i,i+k-1);
}else{
ch = fun(ch,i,ch.length-1);
}
}
return new String(ch);
}
public char[] fun(char[] s, int left, int right){
while(left < right){
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left ++;
right --;
}
return s;
}
}
四、力扣54. 替换数字(第八期模拟笔试)
import java.util.*;
public class Main{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
char[] ch = s.toCharArray();
int count = 0;
for(char c : ch){
if (c < 'a' ){
count ++;
}
}
char[] res = new char[ch.length + count*5];
char[] temp = new char[]{'n','u','m','b','e','r'};
for(int i = 0, j = 0; i < ch.length; i ++){
if(ch[i] < 'a'){
for(int k = 0; k < temp.length; k ++){
res[j++] = temp[k];
}
}else{
res[j++] = ch[i];
}
}
System.out.println(new String(res));
}
}