剑指Offer(java答案)

剑指Offer(java答案)


文章目录

生产者/消费者

public class Main {
    class Message<T> {
        private T message;
        public Message(T message) {
            this.message = message;
        }
    }

    /**
     * 消息队列
     */
    class MessageQueue {
        private LinkedList<Message> queue;
        private int capacity;

        public MessageQueue(int capacity) {
            this.capacity = capacity;
            queue = new LinkedList<>();
        }

        public Message take() {
            synchronized (queue) {
                while (queue.isEmpty()) {
                    //没货了, wait
                    queue.wait();
                }
                Message message = queue.removeFirst();
                queue.notifyAll();
                return message;
            }
        }

        public void put(Message message) {
            synchronized (queue) {
                while (queue.size() == capacity) {
                    //库存已达上限, wait
                    queue.wait();
                }
                queue.addLast(message);
                queue.notifyAll();
            }
        }
    }

    /**
     * 应用
     */
    public void main() {
        MessageQueue messageQueue = new MessageQueue(2);
        // 4 个生产者线程, 下载任务
        for (int i = 0; i < 4; i++) {
            int id = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 生产任务
                    messageQueue.put(new Message("111"));
                }
            }, "生产者" + i).start();
        }
        // 1 个消费者线程, 处理结果
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // 消费任务
                    Message message = messageQueue.take();
                }
            }
        }, "消费者").start();
    }
}

3个线程,交替打印,abcabcabcabcabc

线程 1 输出 a 5 次,线程 2 输出 b 5 次,线程 3 输出 c 5 次。现在要求输出 abcabcabcabcabc 怎么实现

class SyncWaitNotify {
        private int flag;
        private int loopNumber;

        public SyncWaitNotify(int flag, int loopNumber) {
            this.flag = flag;
            this.loopNumber = loopNumber;
        }

        public void print(int waitFlag, int nextFlag, String str) {
            for (int i = 0; i < loopNumber; i++) {
                synchronized (this) {
                    while (this.flag != waitFlag) {
                        this.wait();
                    }
                    System.out.print(str);
                    flag = nextFlag;
                    this.notifyAll();
                }
            }
        }

        /**
         * 应用
         */
        public void main() {
            SyncWaitNotify syncWaitNotify = new SyncWaitNotify(1, 5);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    syncWaitNotify.print(1, 2, "a");
                }
            }).start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    syncWaitNotify.print(2, 3, "b");
                }
            }).start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    syncWaitNotify.print(3, 1, "c");
                }
            }).start();
        }
    }

自定义线程池

/**
     * 1、拒绝策略
     */
    interface RejectPolicy<T> {
        void reject(BlockingQueue<T> queue, T task);
    }

    /**
     * 2、任务队列
     */
    class BlockingQueue<T> {
        // 1. 任务队列
        private Deque<T> queue = new ArrayDeque<>();
        // 2. 锁
        private ReentrantLock lock = new ReentrantLock();
        // 3. 生产者条件变量
        private Condition fullWaitSet = lock.newCondition();
        // 4. 消费者条件变量
        private Condition emptyWaitSet = lock.newCondition();
        // 5. 容量
        private int capcity;

        public BlockingQueue(int capcity) {
            this.capcity = capcity;
        }

        // 阻塞获取
        public T take() {
            lock.lock();
            try {
                while (queue.isEmpty()) {
                    emptyWaitSet.await();
                }
                T t = queue.removeFirst();
                fullWaitSet.signal();
                return t;
            } finally {
                lock.unlock();
            }
        }

        // 阻塞添加
        public void put(T task) {
            lock.lock();
            try {
                while (queue.size() == capcity) {
                    //等待加入任务队列
                    fullWaitSet.await();
                }
                //加入任务队列
                queue.addLast(task);
                emptyWaitSet.signal();
            } finally {
                lock.unlock();
            }
        }

        // 带超时阻塞获取
        public T poll(long timeout, TimeUnit unit) {
            lock.lock();
            try {
                // 将 timeout 统一转换为 纳秒
                long nanos = unit.toNanos(timeout);
                while (queue.isEmpty()) {
                    // 返回值是剩余时间
                    if (nanos <= 0) {
                        return null;
                    }
                    nanos = emptyWaitSet.awaitNanos(nanos);
                }
                T t = queue.removeFirst();
                fullWaitSet.signal();
                return t;
            } finally {
                lock.unlock();
            }
        }

        // 带超时时间阻塞添加
        public boolean offer(T task, long timeout, TimeUnit timeUnit) {
            lock.lock();
            try {
                long nanos = timeUnit.toNanos(timeout);
                while (queue.size() == capcity) {
                    if (nanos <= 0) {
                        return false;
                    }
                    //等待加入任务队列
                    nanos = fullWaitSet.awaitNanos(nanos);
                }
                //加入任务队列
                queue.addLast(task);
                emptyWaitSet.signal();
                return true;
            } finally {
                lock.unlock();
            }
        }

        public int size() {
            lock.lock();
            try {
                return queue.size();
            } finally {
                lock.unlock();
            }
        }

        public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
            lock.lock();
            try {
                // 判断队列是否满
                if (queue.size() == capcity) {
                    rejectPolicy.reject(this, task);
                } else { // 有空闲
                    //加入任务队列
                    queue.addLast(task);
                    emptyWaitSet.signal();
                }
            } finally {
                lock.unlock();
            }
        }
    }

    /**
     * 线程池
     */
    class ThreadPool {
        // 任务队列
        private BlockingQueue<Runnable> taskQueue;
        // 线程集合
        private HashSet<Worker> workers = new HashSet<>();
        // 核心线程数
        private int coreSize;
        // 获取任务时的超时时间
        private long timeout;
        private TimeUnit timeUnit;
        private RejectPolicy<Runnable> rejectPolicy;

        public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity,
                          RejectPolicy<Runnable> rejectPolicy) {
            this.coreSize = coreSize;
            this.timeout = timeout;
            this.timeUnit = timeUnit;
            this.taskQueue = new BlockingQueue<>(queueCapcity);
            this.rejectPolicy = rejectPolicy;
        }

        // 执行任务
        public void execute(Runnable task) {
            // 当任务数没有超过 coreSize 时,直接交给 worker 对象执行
            // 如果任务数超过 coreSize 时,加入任务队列暂存
            synchronized (workers) {
                if (workers.size() < coreSize) {
                    Worker worker = new Worker(task);
                    workers.add(worker);
                    worker.start();
                } else {
                    taskQueue.tryPut(rejectPolicy, task);
                }
            }
        }

        class Worker extends Thread {
            private Runnable task;

            public Worker(Runnable task) {
                this.task = task;
            }

            @Override
            public void run() {
                // 执行任务
                // 1) 当 task 不为空,执行任务
                // 2) 当 task 执行完毕,再接着从任务队列获取任务并执行
                // while(task != null || (task = taskQueue.take()) != null) {
                while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
                    task.run();
                    task = null;
                }
                synchronized (workers) {
                    workers.remove(this);
                }
            }
        }
    }

3、二维数组中的查找

题目描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
| 1| 2| 8|9|
|-|-----| -----|
| 2 | 4 | 9|12|
| 4| 7| 10 |13|
| 6 | 8 | 11 |15|

思路: 从右上角开始,若小,向下走,删除一行,若大,向左走,删除一列

/*
利用二维数组由上到下,由左到右递增的规律,
那么选取右上角或者左下角的元素a[row] [col]与target进行比较,
当target小于元素a[row] [col]时,那么target必定在元素a所在行的左边,
即col--;
当target大于元素a[row][col]时,那么target必定在元素a所在列的下边,
即row++;
*/
public class Solution {
    public boolean Find(int [][] array,int target) {
        int row=0;
        int col=array[0].length-1;
        while(row<=array.length-1&&col>=0){
            if(target==array[row][col])
                return true;
            else if(target>array[row][col])
                row++;
            else
                col--;
        }
        return false; 
    }
}

4、替换空格

题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

思路:先遍历一遍字符,统计空格数,由此计算替换之后的总长度。然后从后往前加载字符串,如果发现空格,就替换20%

/*
问题1:替换字符串,是在原来的字符串上做替换,还是新开辟一个字符串做替换!
问题2:在当前字符串替换,怎么替换才更有效率(不考虑java里现有的replace方法)。
      从前往后替换,后面的字符要不断往后移动,要多次移动,所以效率低下
      从后往前,先计算需要多少空间,然后从后往前移动,则每个字符只为移动一次,这样效率更高一点。
*/
public class Solution {
    public String replaceSpace(StringBuffer str) {
        int spacenum = 0;//spacenum为计算空格数
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)==' ')
                spacenum++;
        }
        int indexold = str.length()-1; //indexold为为替换前的str下标
        int newlength = str.length() + spacenum*2;//计算空格转换成%20之后的str长度
        int indexnew = newlength-1;//indexold为为把空格替换为%20后的str下标
        str.setLength(newlength);//使str的长度扩大到转换成%20之后的长度,防止下标越界
        for(;indexold>=0 && indexold<newlength;--indexold){ 
                if(str.charAt(indexold) == ' '){  //
                str.setCharAt(indexnew--, '0');
                str.setCharAt(indexnew--, '2');
                str.setCharAt(indexnew--, '%');
                }else{
                    str.setCharAt(indexnew--, str.charAt(indexold));
                }
        }
        return str.toString();
    }
}

5、从尾到头打印链表

题目描述:
输入一个链表,从尾到头打印链表每个节点的值。

思路1:栈

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*/
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if(listNode == null){
            ArrayList list = new ArrayList();
            return list;
        }
        Stack<Integer> stk = new Stack<Integer>();
        while(listNode != null){
            stk.push(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> arr = new ArrayList<Integer>();
        while(!stk.isEmpty()){
            arr.add(stk.pop());
        }
        return arr;
    }
}

思路2:递归

public class Solution {
    public void printListFromTailToHead(ListNode listNode) {
      if(listNode != null){
            if(listNode.next != null){
                printListFromTailToHead(listNode.next);
            }
           System.out.print(""+listNode.var);
        }
 
    }
}

6、重建二叉树

题目描述:已知中序和前序,请重建二叉树

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
        return root;
    }
    //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
    private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {  
        if(startPre>endPre||startIn>endIn)
            return null;
        TreeNode root=new TreeNode(pre[startPre]);
        for(int i=startIn;i<=endIn;i++)
            if(in[i]==pre[startPre]){
                root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);  //注意pre的位置,要用偏移量,不能用i,因为i是在变化              
                root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
            }                 
        return root;
    }
}

引申:已知中序和后序求前序

package com.zhuang.tree;

public class Main {
	
	 public static class TreeNode {
	      int val;
	      TreeNode left;
	      TreeNode right;
	      TreeNode(int x) { val = x; }
	  }
	
	 public static TreeNode reConstructBinaryTree(int [] post,int [] in) {
	        TreeNode root=reConstructBinaryTree(post,0,post.length-1,in,0,in.length-1);
	        return root;
	    }
	 
	 
	    private static TreeNode reConstructBinaryTree(int [] post,int startPost,int endPost,int [] in,int startIn,int endIn) {
	         
	        if(startPost>endPost||startIn>endIn)
	            return null;
	        
	        TreeNode root=new TreeNode(post[endPost]);
	         
	        for(int i=startIn;i<=endIn;i++)
	            if(in[i]==post[endPost]){
	                root.left=reConstructBinaryTree(post,startPost,startPost+i-startIn-1,in,startIn,i-1);
	                root.right=reConstructBinaryTree(post,startPost+i-startIn,endPost-1,in,i+1,endIn);
	            }
	                 
	        return root;
	    }
	    
	    public static void preOrder(TreeNode root){
	    	if(root == null){
	    		return;
	    	}
	    	System.out.println(root.val);
	    	preOrder(root.left);
	    	preOrder(root.right);
	    }
	    
	    public static void main(String[] args){
	    	int[] post = {2,4,3,1,6,7,5};
	    	int[] in = {1,2,3,4,5,6,7};
	    	TreeNode root = reConstructBinaryTree(post, in);
	    	preOrder(root);
	    }
}

7、用两个栈实现队列

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:入栈给stack1,出栈时,若stack2不为空,则出栈,若为空,把stack1的内容全都放入stack2,然后再出栈

import java.util.Stack;
 
public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
     
   public void push(int node) {
        stack1.push(node);
    }
     
     
   public int pop() {
        
       while(!stack2.isEmpty())
        {
            return stack2.pop();
        }
         
        while(!stack1.isEmpty())
        {
            stack2.push(stack1.pop());
        }
        
        return stack2.pop();
    }
}

8、旋转数组的最小数字

题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

import java.util.ArrayList;

public class Solution {
	/*
	 * 传进去旋转数组,注意旋转数组的特性: 1.包含两个有序序列 2.最小数一定位于第二个序列的开头 3.前序列的值都>=后序列的值
	 */

	// 用到了快速排序的快速定位范围的思想,
	public int minNumberInRotateArray(int[] array) {

		if (array == null || array.length == 0) {
			return 0;
		}
		int low = 0;//指向第一个
		int up = array.length - 1;//指向最后一个
		int mid = low;

		// 当low和up两个指针相邻时候,就找到了最小值,也就是
		// 右边序列的第一个值

		while (array[low] >= array[up]) {
			if (up - low == 1) {
				mid = up;
				break;
			}
			// 如果low、up、mid下标所指的值恰巧相等
			// 如:{0,1,1,1,1}的旋转数组{1,1,1,0,1}
			if (array[low] == array[up] && array[mid] == array[low])
				return MinInOrder(array);
			mid = (low + up) / 2;
			// 这种情况,array[mid]仍然在左边序列中
			if (array[mid] >= array[low])
				low = mid;// 注意,不能写成low=mid+1;
			// 要是这种情况,array[mid]仍然在右边序列中
			else if (array[mid] <= array[up])
				up = mid;
		}

		return array[mid];

	}

	private int MinInOrder(int[] array) {
		// TODO Auto-generated method stub
		int min = array[0];
		for (int i = 1; i < array.length; i++) {
			if (array[i] < min) {
				min = array[i];

			}
		}
		return min;
	}

}

9、斐波那契数列

题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

思路1:递归,简洁但效率不高

public int Fibonacci(int n) {        
        if(n<=0)
            return 0;
        if(n==1)
            return 1;
        return Fibonacci(n-1) + Fibonacci(n-2); 
    }

思路2:循环,O(N)

public class Solution {
    public int Fibonacci(int n) {
        int preNum=1;
        int prePreNum=0;
        int result=0;
        if(n==0)
            return 0;
        if(n==1)
            return 1;
        for(int i=2;i<=n;i++){
            result=preNum+prePreNum;
            prePreNum=preNum;
            preNum=result;
        }
        return result;
 
    }
}

扩展1:跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

思路:斐波拉契数序列,初始条件n=1:只能一种方法,n=2:两种
对于第n个台阶来说,只能从n-1或者n-2的台阶跳上来,所以
F(n) = F(n-1) + F(n-2)

扩展2:变态跳台阶

题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

思路:
因为n级台阶,第一步有n种跳法:跳1级、跳2级、到跳n级
跳1级,剩下n-1级,则剩下跳法是f(n-1)
跳2级,剩下n-2级,则剩下跳法是f(n-2)
所以f(n)=f(n-1)+f(n-2)+…+f(1)
因为f(n-1)=f(n-2)+f(n-3)+…+f(1)
所以f(n)=2*f(n-1)
所以f(n)=2的(n-1)次幂

public class Solution {
    public int JumpFloorII(int target) {
        if(target<=0)
            return 0;
        return 1<<(target-1);
    }
}

10、二进制中1的个数

题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

最差的解法:因为要考虑负数的问题,若是负数,因为要保证一直输负数,多以第一位一直为1,最后会变成0XFFFFFFFF,造成死循环

public class Solution {
public int  NumberOf1(int n) {
        int count= 0;
        int flag = 1;
        while (n!= 0){
            if ((n & 1) != 0){
                count++;      
            }
            n = n>>1;
        }
         return count;
     }    
}

改进的解法:

public class Solution {
public int  NumberOf1(int n) {
        int count= 0;
        int flag = 1;
        while (flag != 0){
            if ((n & flag) != 0){
                count++;      
            }
            flag  = flag << 1;
        }
         return count;
     }    
}

最精妙的解法:

public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        while(n!= 0){
            count++;
            n = n & (n - 1);//每一次将最后一个1变成0
         }
        return count;
    }
}

11、数值的整数次方

题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

**思路1:**本题主要考虑边界问题,全面不够高效的解法,注意:由于计算机表示小数(包括float和double型小数)都有误差,我们不能直接用==判断两个小数是否相等,如果两个小数的差的绝对值很小,比如小于0.0000001,就可以认为他们相等

public class Solution {
    public double Power(double base, int exponent) {
        double res = 0.0;
        if (equal(base, 0.0) && exponent < 0) {
            throw new RuntimeException("0的负数次幂没有意义");
        }
        // 这里定义0的0次方为1
        if (exponent == 0) {
            return 1.0;
        }
        if (exponent < 0) {
            res = powerWithExponent(1.0/base, -exponent);
        } else {
            res = powerWithExponent(base, exponent);
        }
        return res;
    }
     
    private double powerWithExponent(double base, int exponent) {
        double res = 1.0;
        for (int i = 1; i <= exponent; i++) {
            res = res * base;
        }
        return res;
    }
     
    // 判断double类型的数据
    private boolean equal(double num1, double num2) {
        if (Math.abs(num1 - num2) < 0.0000001) {
            return true;
        }
        return false;
    }
}

思路2:n为偶数时:an=an/2 * a^n/2;
n为奇数,an=(a(n-1)/2)* (a^(n-1/2))* a
所以对乘法处进行优化,如果是32次方,等于16次方*16次方

 /*
    ** 对乘法进行优化的部分
    */
    private double powerWithExponent(double base, int exponent) {
        if(exponent==0){
            return 1;
        }
         
        if(exponent==1){
            return base;
        }
         
       double result = powerWithExponent(base,exponent>>1);//每次除以2
       result*=result;//最后相乘,如果是奇数,还要乘一个
        
        //如果是奇数次方的情况,最终除2余1要与base相乘
        if((exponent & 0x1)==1){
            result *= base;
        }
        return result;
    }

12、打印1到最大的n位数

题目描述:如n=3,则从1打印到999

public class Solution {

	// ====================方法一====================
	public static void Print1ToMaxOfNDigits(int n) {
		if (n <= 0)
			return;

		char[] number = new char[n];
		
		//每一个字符设为0
		for (int i = 0; i < n; i++) {
			number[i] = '0';
		}

		while (!Increment(number)) {//如果加法溢出,则退出,否则打印数字
			PrintNumber(number);
		}

	}

	// 字符串number表示一个数字,在 number上增加1
	// 如果做加法溢出,则返回true;否则为false
	public static boolean Increment(char[] number) {
		boolean isOverflow = false;//溢出标志
		int nTakeOver = 0;//进位
		int nLength = number.length;

		for (int i = nLength - 1; i >= 0; i--) {//从后向前,最后一位数字加1
			int nSum = number[i] - '0' + nTakeOver;
			if (i == nLength - 1)
				nSum++;

			if (nSum >= 10) {
				if (i == 0)
					isOverflow = true;
				else {
					nSum -= 10;
					nTakeOver = 1;
					number[i] = (char) ('0' + nSum);
				}
			} else {
				number[i] = (char) ('0' + nSum);
				break;
			}
		}

		return isOverflow;
	}

	// 字符串number表示一个数字,数字有若干个0开头
	// 打印出这个数字,并忽略开头的0
	public static void PrintNumber(char[] number) {
		boolean isBeginning0 = true;
		int nLength = number.length;

		//标志位的思想,从第一位不为0的数字开始打印,如000123,打印123
		for (int i = 0; i < nLength; ++i) {
			if (isBeginning0 && number[i] != '0')
				isBeginning0 = false;

			if (!isBeginning0) {
				System.out.print(number[i]);
			}
		}
		System.out.println();
	}
}

思路2:用递归,代码简洁,思路不好想,每一位都是从0到9的全排列

public class Solution {

	// // ====================方法二:递归====================
	public static void Print1ToMaxOfNDigits(int n) {
		if (n <= 0)
			return;

		char[] number = new char[n];

		for (int i = 0; i < 10; ++i) {
			number[0] = (char) (i + '0');
			Print1ToMaxOfNDigitsRecursively(number, n, 0);
		}

	}

	public static void Print1ToMaxOfNDigitsRecursively(char[] number, int length,int index) {
		if (index == length - 1) {
			PrintNumber(number);
			return;
		}

		for (int i = 0; i < 10; ++i) {
			number[index + 1] = (char) (i + '0');
			Print1ToMaxOfNDigitsRecursively(number, length, index + 1);
		}
	}

	// 字符串number表示一个数字,数字有若干个0开头
	// 打印出这个数字,并忽略开头的0
	public static void PrintNumber(char[] number) {
		boolean isBeginning0 = true;
		int nLength = number.length;

		// 标志位的思想,从第一位不为0的数字开始打印,如000123,打印123
		for (int i = 0; i < nLength; ++i) {
			if (isBeginning0 && number[i] != '0')
				isBeginning0 = false;

			if (!isBeginning0) {
				System.out.print(number[i]);
			}
		}
		System.out.println();
	}
}

13、在O(1)时间删除链表结点

给定单向链表头指针和一个节点指针,在O(1)时间删除链表结点

/*
	对于删除节点,我们普通的思路就是让该结点的前一个节点指向改节点的下一个节点
	*/
	public void delete(Node head, Node toDelete){
	    if(toDelete == null){
	        return ;
	    }
	    if(toDelete.next != null){//删除的节点不是尾节点
	        toDelete.val = toDelete.next.val;
	        toDelete.next = toDelete.next.next;
	    }else if(head == toDelete){//链表只有一个节点,删除头结点也是尾节点
	    	head = null;
	    }else{ //删除的节点是尾节点的情况
	        Node node = head;
	        while(node.next != toDelete){//找到倒数第二个节点
	            node = node.next;
	        }
	        node.next = null;
	    }
	}

14、调整数组顺序使奇数位于偶数前面

题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

public class Solution {
    public void reOrderArray(int [] array) {
        //注释的部分使用快速排序的算法,很明显快速排序是不稳定的,这里需要用归并排序
        /*
        if(array.length == 0){
            return;
        }
        int high = array.length - 1;
        int low = 0;
        while(low < high){
            while(low < high && array[low] % 2 == 1){
                low ++;
            }
            while(low < high && array[high] % 2 == 0){
                high --;
            }
            int temp = array[low];
            array[low] = array[high];
            array[high] = temp;
        }*/
        
        //用用归并排序的思想,因为归并排序是稳定的
        int length = array.length;
        if(length == 0){
            return;
        }
        int[]
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值