合并有序数组 合并有序链表 迭代 递归

 

TODO 

// 非降序
func mergeOrdered(a, b []int) []int {
    m := len(a)
    n := len(b)
    if m == 0 {
        return b
    }
    if n == 0 {
        return a
    }
    if m+n == 0 {
        return a
    }
    ia := 0
    ib := 0
    c := m + n
    var r []int

    for i := 0; i < c; i++ {
        r = append(r, 0)
        var v int
        if ia < m {
            if ib < n {
                if a[ia] > b[ib] {
                    v = b[ib]
                    ib++
                } else {
                    v = a[ia]
                    ia++
                }
            } else {
                v = a[ia]
                ia++
            }
        } else {
            v = b[ib]
            ib++
        }
        r[i] = v
    }
    return r
}


 

https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/

21. 合并两个有序链表

 

 

递归

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	if list1 == nil && list2 == nil {
		return nil
	}
	if list1 == nil {
		return list2
	}
	if list2 == nil {
		return list1
	}
	node := &ListNode{}
	if list1.Val < list2.Val {
		node.Val = list1.Val
		node.Next = mergeTwoLists(list1.Next, list2)
	} else {
		node.Val = list2.Val
		node.Next = mergeTwoLists(list1, list2.Next)
	}
	return node
}

  

 

迭代

 

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	if list1 == nil && list2 == nil {
		return nil
	}
	if list1 == nil {
		return list2
	}
	if list2 == nil {
		return list1
	}
	var node *ListNode
	var l []*ListNode
	for {
		if list1 == nil && list2 == nil {
			break
		}
		n := &ListNode{}
		if list1 != nil {
			if list2 != nil {
				if list1.Val > list2.Val {
					n.Val = list2.Val
					list2 = list2.Next
					l = append(l, n)
					continue
				}
			}
			n.Val = list1.Val
			list1 = list1.Next
		} else {
			n.Val = list2.Val
			list2 = list2.Next
		}
		l = append(l, n)
	}
	n := len(l)
	for i := 0; i < n; i++ {
		j := &ListNode{Val: l[n-1-i].Val}
		j.Next = node
		node = j
	}
	return node
}

  

 

posted @ 2019-01-18 06:52  papering  阅读(247)  评论(0编辑  收藏  举报