Guest User

Untitled

a guest
Jul 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. /**
  2. * Given two sorted integer arrays A and B, merge B into A as one sorted array.
  3. * Note: You may assume that A has enough space (size that greated or equal to m + n) to hold
  4. * additional elements from B. The Number of elements initialized in A and B are m and n respectively.
  5. *
  6. * Idea: 从后向前排(从前往后会导致A数组数据丢失)
  7. */
  8. fun merge(array1: Array<Int>, n: Int, array2: Array<Int>, m: Int) : Array<Int> {
  9. var index = n + m - 1
  10. var i = n - 1
  11. var j = m - 1
  12. while (index >= 0) {
  13. when {
  14. i >= 0 && j >= 0 -> {
  15. if (array1[i] > array2[j]) {
  16. array1[index] = array1[i]
  17. i --
  18. } else {
  19. array1[index] = array2[j]
  20. j --
  21. }
  22. }
  23. i >= 0 -> {
  24. array1[index] = array1[i]
  25. i --
  26. }
  27. j >= 0 -> {
  28. array1[index] = array2[j]
  29. j --
  30. }
  31. }
  32. index --
  33. }
  34. return array1
  35. }
Add Comment
Please, Sign In to add comment