Love丶FFC's Blog

LintCode_easy:合并排序数组

2019-08-24 19:37:43
阅读:558   •   评论:4
标签:,

描述

合并两个有序升序的整数数组A和B变成一个新的数组。新数组也要有序。

样例

样例1:

输入: A=[1], B=[1]
输出:[1,1]	
样例解释: 返回合并后的数组。

样例2:

输入: A=[1,2,3,4], B=[2,4,5,6]
输出: [1,2,2,3,4,4,5,6]	
样例解释: 返回合并后的数组。

挑战

你能否优化你的算法,如果其中一个数组很大而另一个数组很小?

编程语言:Java

解题思想:

1.创建一个新数组,长度为A数组长度+B数组长度。

2.逐一赋值。

3.冒泡排序。

时间复杂度:O(n^2)

IDE代码如下:

  1. package LintCode_Easy;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class _6 {
  6.  
  7. public static void main(String[] args) {
  8. int[] A = new int[] {1,2,3,4};
  9. int[] B = new int[] {2,4,5,6};
  10. int[] C = new int[A.length+B.length];
  11. int swap = 0;
  12. for(int i=0;i<A.length;i++)
  13. C[i]=A[i];
  14. for(int i=A.length,j=0;j<B.length;i++,j++) //C的起始索引=A的长度
  15. C[i]=B[j];
  16. for(int i=0;i<C.length;i++)
  17. for(int j=i;j<C.length;j++)
  18. {
  19. if(C[i]>C[j])
  20. {
  21. swap=C[j];
  22. C[j]=C[i];
  23. C[i]=swap;
  24. }
  25. }
  26. System.out.println(Arrays.toString(C));
  27. }
  28.  
  29. }

LintCode编辑器代码如下:

  1. public class Solution {
  2. public int[] mergeSortedArray(int[] A, int[] B) {
  3. int[] C = new int[A.length+B.length];
  4. int swap = 0;
  5. for(int i=0;i<A.length;i++)
  6. C[i]=A[i];
  7. for(int i=A.length,j=0;j<B.length;i++,j++)
  8. C[i]=B[j];
  9. for(int i=0;i<C.length;i++)
  10. for(int j=i;j<C.length;j++)
  11. {
  12. if(C[i]>C[j])
  13. {
  14. swap=C[j];
  15. C[j]=C[i];
  16. C[i]=swap;
  17. }
  18. }
  19. return C;
  20. }
  21. }

评论板

共有 4 条评论

  1. Jorcift

    HUGO Gene Symbol for the gene concept generic cialis tadalafil

  2. intuido

    buy priligy dapoxetine online Admittedly, innovativeness is not a phenomenon reserved for the digital area; nevertheless it is in the digital world that it emerges the most

  3. intuido

    viagra and cialis online Drug induced anti Ro positive subacute cutaneous lupus in a man treated with olmesartan

  4. zjOvUlkb

    buy cialis online from india To date, only 20 cases have been reported 8

--------查看该分类下最新文章--------
^
新版博客正在完善中!域名:http://www.loveffc:8080,点击跳转,完全移植后将去除端口号。

Copyright © 2018 - 2021 FFC的小站 - 滇 ICP 备 18010780 号 - 1

- Powered by WordPress & AliYun · Theme by FFC -

- Environment by Windows & XAMPP · Designed by WebStorm & VSCode -

已运行:

访问量:491311