Problem 3:
Merge two given sorted integer array A and B into a new sorted integer array.
解释:
两个有序数组A和B结合,要先自己声明一个数组C,C中的元素依次由A和B中元素比较得来,每个数组都要有记录当前位置的index。
(自己写的时候半天AC不了,用IDE调试发现是我初始化的问题,index 没有初始化为0,int类型编译器应该给我随便赋了一个值)
代码:
class Solution {
public:
/*
* @param A: sorted integer array A
* @param B: sorted integer array B
* @return: A new sorted integer array
*/
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
// write your code here
int x = A.size();
int y = B.size();
vector<int> C(x+y);
int i = 0, j = 0,k = 0;
while(i < x && j < y){
if(A[i]<B[j]){
C[k++] = A[i++];
}
else{
C[k++] = B[j++];
}
}
while(i<x){
C[k++] = A[i++];
}
while(j<y){
C[k++] = B[j++];
}
return C;
}
};
后续:
关于int类型未初始化的问题:
若编码时int 类型的变量未初始化,全局变量、静态变量默认初始化为0,局部变量为随机值。
再捂脸复习一下哪些是全局变量,哪些是局部变量:
在函数内定义的变量都是局部变量,作用域仅在函数内部。形参也是局部变量,实参给形参传值的过程也是给局部变量赋值的过程;如
int main(){
int m,n; //m,n仅在函数main()内有效
return 0;
}
m,n都是局部变量。
在函数外声明的为全局变量,作用域为整个程序, 也就是所有的.c和.h文件,可以通过extern 链接操作。