两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if(nums == null || nums.length == 0){
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
}
map.put(nums[i], i);
}
return res;
}
}
反转字符串
没啥好说的,又是双指针
class Solution {
public void reverseString(char[] s) {
int l = 0, r = s.length - 1;
while(l < r) {
char t = s[l];
s[l++] = s[r];
s[r--] = t;
}
}
}
反转字符串 II
class Solution {
public String reverseStr(String s, int k) {
char[] cs = s.toCharArray();
int n = s.length();
for (int l = 0; l < n; l = l + 2 * k) {
int r = l + k - 1;
reverse(cs, l, Math.min(r, n - 1));
}
return String.valueOf(cs);
}
void reverse(char[] cs, int l, int r) {
while (l < r) {
char c = cs[l];
cs[l] = cs[r];
cs[r] = c;
l++; r--;
}
}
}