
Array
- introduction
- 1D Array:Array is a container for storing multiple item of same type. * 2D Array: if the sub containers also is a same type sub containers.
- initizaliation
- 1D array:
1
21. int [] array = new int[length];
2. int [] array = new int [] {1,2,3}; - 2D array: same but have two square bracket
- 1D array:
- unsorted array method
- add() with bug
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static int [] arrayAdd(int [] A, int target) {
int [] res = new int [A.length+1];
int idx = 0;
for (int a : A){
res[idx++] = a;
}
res[A.length] = target;
A = res;
return A;
}
//(2)
public static int [] arrayAddidx(int [] A, int target, int idx) {
int [] res= new int [A.length+1];
if (idx > A.length-1 || idx < 0) {
System.out.println("Wrong index. ..");
return A;
}
for (int i = 0; i< idx; i++) {
res[i]=A[i];
}
res[idx] = target;
for (int j = idx; j< A.length; j++) {
res[j+1]=A[j];
}
A = res;
return A;
} - contains() with bug
- add() with bug
1
2
3
4
5
6
7
8
9
10
11
12 public static int contains(int [] A, int target) {
int index = 0;
for (Integer a: A) {
if (a.equals(target)){
return index;
}
else {
index++;
}
}
return -1;
}* modify() with bug
1
2
3
4
5
6
7
8
9 public static boolean (int [] A, int idx, int target) {
boolean istrue=false;
if (idx > A.length - 1 || idx < 0) {
return istrue;
}
A[idx]= target;
return A[idx]== target;
}8 delete() with bug
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 public static int [] delete (int [] A, int target) {
boolean isdelete = false;
int n = A.length;
if (contains (A, target) != -1) {
int i;
for (i = 0; i < n; i++) {
if (A[i]==target) {
break;
}
}
if (i < n) {
n = n - 1;
for (int j = i; j< n; j++) {
A[j] = A[j+1];
}
}
}
int k=0;
int [] res= new int[A.length - 1];
for (int a : A) {
if (k<=A.length - 2) {
res[k++]=a;
}
}
A = res;
return A;
}DataScale
* O(n)-> 10^8 *




近期评论