题目
https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
分析
方法一:使用直接方法 ,开辟俩个数组,一个存储奇数,一个存储偶数,时间和空间复杂度都是o(n)
方法二:使用快慢指针 ,时间复杂度为o(n) 因为原地计算,空间复杂度为o(1)
代码
public class Solution1 {
public ListNode deleteNode(ListNode head, int val) {
if(head.val==val){
return head.next;
}
return null;
}
public int[] exchangeWay1(int[] nums) {
if(nums==null){
return nums;
}
List<Integer> oddNumbers = new ArrayList();
List<Integer> ovenNumbers = new ArrayList();
for(int i =0 ;i<nums.length;i++){
if(nums[i]%2!=0){
oddNumbers.add(nums[i]);
}else{
ovenNumbers.add(nums[i]);
}
}
oddNumbers.addAll(ovenNumbers);
int totalSize = oddNumbers.size() ;
int[] arr = new int[totalSize];
for (int i = 0; i < oddNumbers.size(); i++) {
arr[i] = oddNumbers.get(i);
}
return arr;
}
/**
*
* @date: 2020-04-18 16:57
* @param: * @param nums:
* @return: * @return: int[]
* @author: wwh
* @Description: 使得奇数在前 偶数在后 快慢指针的方法
* 时间复杂度o(n)
空间复杂度o(1)
*/
public int[] exchangeWay2(int[] nums) {
if(nums==null||nums.length==0){
return nums;
}
int start = 0;
int end = nums.length-1;
while (start!=end){
if(nums[start]%2==0){
if(nums[end]%2==1){
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
}else {
end--;
}
}else {
start++;
}
}
return nums;
}
public static void main(String[] args) {
Solution1 a = new Solution1();
int[] arr = {1,2,3,4};
int[] exchange = a.exchangeWay2(arr);
System.out.println(exchange);
}
}
后记
因为题目有可能变为把正数和负数,把素数和非素数等等,为了后期变化 要把判断逻辑抽离出来,使得维护更加简单