算法(四十三)

48 篇文章 0 订阅

1、存储有[0,n)的数组,数组长度为len。只能交换数组里n和0的位置进行排序.
输入 数组a为:{3,4,2,5,1,0,9,7,8,6}
输出 数组a为:{0 1 2 3 4 5 6 7 8 9}
public class test003 {
    public static void main(String[] args) {
        int[] a = new int[]{3,4,2,5,1,0,9,7,8,6};
        sort(a, a.length);
        for(int i=0; i<a.length; i++){
            System.out.print(a[i]+" ");
        }
    }

    private static void sort(int[] a, int len){
        for(int i=0; i<len; i++){
            swap_with_zero(a, len, i,a[i]);
            swap_with_zero(a, len, i,i);
        }
    }

    private static void swap_with_zero(int[] a, int len, int i, int num) {
       if(a[i] == num){
           a[i] =0;
       }else if(a[i] == 0){
           a[i] =i;
       }
    }
}
 

2、一个链表:奇数序号升序,偶数序号降序,要求做这个链表的整体升序排序。
例子:1 8 3 6 5 4 7 2 9,最后输出1 2 3 4 5 6 7 8 9。
思路:
分成三步
(1)首先根据奇数位和偶数位拆分成两个链表。
(2)然后对偶数链表进行反转。
(3)最后将两个有序链表进行合并。
public class test004 {
    public ListNode sort(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode evenHead = getEvenHead(head);
        return merge(head, reverse(evenHead));
    }
    private ListNode getEvenHead(ListNode head) {
        ListNode cur = head;
        ListNode dummyEven = new ListNode(0);
        ListNode curEven = dummyEven;
        while (cur != null && cur.next != null) {
            ListNode next = cur.next;
            cur.next = next.next;
            next.next = null;
            cur = cur.next;
            
            curEven.next = next;
            curEven = curEven.next;
        }
        return dummyEven.next;
    }
    private ListNode reverse(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
    private ListNode merge(ListNode one, ListNode two) {
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        while (one != null && two != null) {
            if (one.val < two.val) {
                cur.next = one;
                one = one.next;
            } else {
                cur.next = two;
                two = two.next;
            }
            cur = cur.next;
        }
        cur.next = one == null ? two : one;
        return dummyHead.next;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值