27.
题目:
想法:双指针分别从头尾判断两数的奇偶,往中间移动或交换
class Solution {
public int[] exchange(int[] nums) {
int i=0;
int j=nums.length-1;
while(i<j){
if((nums[i]&1)==0 && (nums[j]&1)==1){//偶 奇
int tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
i++;j--;
}
else if((nums[i]&1)==1 && (nums[j]&1)==1)//奇 奇
i++;
else if((nums[i]&1)==0 && (nums[j]&1)==0)//偶 偶
j--;
else{//奇 偶
i++;
j--;
}
}
return nums;
}
}
结果:
57.
题目:
剑指 Offer 57. 和为s的两个数字https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/
代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
int i=0;
int j=nums.length-1;
while(i<j){
if(target-nums[j]<nums[i])
//说明j指的太大了
j--;
else if(target-nums[i]>nums[j])
//说明i指的太小了
i++;
else
break;
}
return new int[]{nums[i],nums[j]};
}
}
结果:
58Ⅰ.
题目:
剑指 Offer 58 - I. 翻转单词顺序https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
一开始看成了反转所有字符,从字符入手,得不到正确结果.后参考他人意识到应从单词入手
参考 https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/solution/mian-shi-ti-58-i-fan-zhuan-dan-ci-shun-xu-shuang-z/
想法一: 将字符串以空格分割成字符串数组,存放每个单词,倒序遍历拼接即可,注意遇到字符串应跳过.
代码一:
class Solution {
public String reverseWords(String s) {
String[] strs = s.trim().split(" "); // 删除首尾空格,分割字符串
StringBuilder res = new StringBuilder();
for(int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表
if(strs[i].equals(""))
continue; // 遇到空字符串则跳过
res.append(strs[i] + " "); // 将单词拼接至 StringBuilder
}
return res.toString().trim(); // 转化为字符串,删除尾部空格,并返回
}
}
结果:
想法二:使用双指针,倒序遍历字符串,依次取出子串(单词),过程中跳过空格.
class Solution {
public String reverseWords(String s) {
s = s.trim(); // 删除首尾空格
//倒序搜索
int j = s.length() - 1, i = j;
StringBuilder res = new StringBuilder();
while(i >= 0) {
while(i >= 0 && s.charAt(i) != ' ')
i--; // 搜索首个空格
res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
while(i >= 0 && s.charAt(i) == ' ')
i--; // 跳过单词间空格
j = i; // j 指向下个单词的尾字符
}
return res.toString().trim(); // 转化为字符串并返回
}
}
结果: