class Solution {
public int[] exchange(int[] nums) {
int i = 0, j = nums.length - 1, tmp;
while(i < j){
while(i < j && (nums[i] & 1) == 1)//如果是奇数就跳过该数,直到找到偶数
i++;
while(i < j && (nums[j] & 1) == 0)//同上,直到找到奇数
j--;
tmp = nums[i];//交换上述找的奇数和偶数
nums[i] = nums[j];
nums[j] = tmp;
}
return nums;
}
}
注: n & 1位运算等价于 n % 2取余运算,都可以用于判断数字奇偶性
class Solution {
public int[] twoSum(int[] nums, int target) {
int i = 0, j = nums.length - 1;//对撞双指针
while(i < j){
int s = nums[i] + nums[j];
if(s < target)
i++;
else if(s > target)
j--;
else
return new int[] {nums[i] ,nums[j]};
}
return new int[0];
}
}
对撞双指针: 双指针i, 分别指向数组nums的左右两端
public class Solution{
public boolean hasCycle(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return false;
}
}
快慢指针
快指针走两步,慢指针走一步,最终一定会相遇,代表有环
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
fast = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
}
import java.util.*;
public class Solution {
public boolean judge (String str) {
if(str == null || str.length() == 0){
return false;
}
for(int i = 0, j = str.length() - 1; i < j; i++, j--){
if(str.charAt(i) != str.charAt(j)){
return false;
}
}
return true;
}
}