关于leetcode:将两个有序数组合并为一个有序数组

5次阅读

共计 932 个字符,预计需要花费 3 分钟才能阅读完成。

题目 :给定两个有序数组,将其合并为一个有序数组。
思路:采纳双指针的形式,顺次遍历两个数组 a,b。而后比照两个数组各个地位的元素,a 小于 b,则将 a 的元素存入新数组,而后 a 的指针加 1,a==b,则将两个元素都放入新数组,下标都加 1,如果 a 大于 b,则将 b 的元素放入新数组,而后 b 的指针加 1。

代码

go

func combine(a, b []int) {
    left,right := 0,0

    lena,lenb := len(a),len(b)

    res := make([]int, 0)

    for {
        if left == lena {res = append(res, b[right:]...)
            break
        }

        if  right == lenb {res = append(res, a[left:]...)
            break
        }

        if a[left] < b[right] {res = append(res, a[left])
            left++
        } else if a[left] == b[right] {res = append(res, []int{a[left], b[right]}...)
            left++
            right++
        } else {res = append(res, b[right])
            right++
        }
    }

    fmt.Println(res)
}

php


function test($a, $b):array {$lena = count($a);
    $lenb = count($b);

    $res = [];

    $left = $right = 0;

    while ($left < $lena && $right < $lenb) {if ($a[$left] < $b[$right]) {$res[] = $a[$left];
            $left++;
        } else if ($a[$left] == $b[$right]) {$res[] = $a[$left];
            $res[] = $b[$right];
            $left++;
            $right++;
        } else {$res[] = $b[$right];
            $right++;
        }
    }

    if ($left == $lena) {$res = array_merge($res, array_slice($b, $right));
    }

    if ($right == $lenb) {$res = array_merge($res, array_slice($a, $left));
    }

    return $res;
}
正文完
 0