Leetcode剑指Offer刷题指南:
解法:双指针交换(易理解版)
class Solution {
public int[] exchange(int[] nums) {
int start = 0, end = nums.length - 1;
while (start < end - 1) {
//start处为奇数时往后走
if (nums[start] % 2 != 0) {
start++;
}
//end处为偶数时往前走
if (nums[end] % 2 == 0) {
end--;
}
//start处为偶数,end处为奇数时,进行交换
if (nums[start] % 2 == 0 && nums[end] % 2 != 0) {
swap(nums, start, end);
}
}
return nums;
}
private void swap(int[] nums, int start, int end) {
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
}
}
优化版:
class Solution {
public int[] exchange(int[] nums) {
int start = 0, end = nums.length - 1;
while (start <= end) {
if (nums[start] % 2 != 0) {
start++;
} else if (nums[end] % 2 == 0) {
end--;
} else {
swap(nums, start, end);
}
}
return nums;
}
private void swap(int[] nums, int start, int end) {
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
}
}
简化版:
class Solution {
public int[] exchange(int[] nums) {
int start = 0, end = nums.length - 1;
while (start <= end) {
if (nums[start] % 2 == 1) {
start++;
} else if (nums[end] % 2 == 0) {
end--;
} else {
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
}
}
return nums;
}
}
解法一:HashSet
class Solution {
public int[] twoSum(int[] nums, int target) {
HashSet<Integer> set = new HashSet<>();
for (int x : nums) {
if (!set.contains(target - x)) {
set.add(x);
} else {
return new int[]{x, target - x};
}
}
return null;
}
}
解法二:二分法
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; ++i) {
int x = target - nums[i];
int left = i, right = nums.length - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (x < nums[mid]) {
right = mid - 1;
} else if (x > nums[mid]) {
left = mid + 1;
} else {
return new int[]{nums[i], nums[mid]};
}
}
}
return null;
}
}
解法三:双指针
class Solution {
public int[] twoSum(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
return new int[]{nums[left], nums[right]};
}
}
return null;
}
}
解法一:分割 + 倒序
class Solution {
public String reverseWords(String s) {
String[] strs = s.trim().split(" ");
StringBuilder sb = new StringBuilder();
for (int i = strs.length - 1; i >= 0; --i) {
if (strs[i].equals("")) {
continue;
}
sb.append(strs[i].trim());
if (i == 0) {
break;
} else {
sb.append(" ");
}
}
return sb.toString();
}
}
解法二:双指针
class Solution {
public String reverseWords(String s) {
//去掉前后空格
s = s.trim();
StringBuilder sb = new StringBuilder();
int left = s.length() - 1, right = left;
while (left >= 0) {
//找到第一个空格位置
while (left >= 0 && s.charAt(left) != ' ') {
left--;
}
//添加找到的第一个空格后的第一个单词
sb.append(s.substring(left + 1, right + 1)).append(" ");
//跳过中间空格,找到空格前的位置
while (left >= 0 && s.charAt(left) == ' ') {
left--;
}
right = left;
}
return sb.toString().trim();
}
}