## 1.数组的基础理论

Q:java中二维数组在内存的空间地址是连续的么？

``````public static void test_arr() {

int[][] arr = {

{

1, 2, 3}, {

3, 4, 5}, {

6, 7, 8}, {

9,9,9}};
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
}
``````

``````[I@7852e922
[I@4e25154f
[I@70dea4e
[I@5c647e05
``````

## 2.二分查找

(1)数组是有序的
(2)数组元素不重复(一旦重复，则返回的结果可能是多个)

``````class Solution {

public int search(int[] nums, int target) {

// 注意第一次调用right为nums.length-1,而不是nums.length
return BinarySearch(nums, target, 0, nums.length-1);
}

public int BinarySearch(int [] nums,int target, int left, int right) {

if(left > right) {

return -1;
}
int mid = (left + right)/2;
if(nums[mid] == target) {

return mid;
} else if(nums[mid] < target) {

return BinarySearch(nums, target, mid + 1, right);
} else if(nums[mid] > target) {

return BinarySearch(nums, target, left, mid-1);
}

return -1;
}
``````

``````class Solution {

public int search(int[] nums, int target) {

// 注意第一次调用right为nums.length-1,而不是nums.length
return BinarySearch(nums, target, 0, nums.length-1);
}

public int BinarySearch(int [] nums,int target, int left, int right) {

while(left <= right) {

int mid = (left + right)/2;
if(nums[mid] == target) {

return mid;
} else if(nums[mid] < target) {

return BinarySearch(nums, target, mid + 1, right);
} else if(nums[mid] > target) {

return BinarySearch(nums, target, left, mid-1);
}

}

return -1;
}
}
``````

## 3 移除元素

(1)算法原地工作

(2)数组的元素在内存地址中是连续的，不能单独删除数组中的某个元素，只能覆盖。

``````class Solution {

public int removeElement(int[] nums, int val) {

int count = 0;
for(int i = 0; i <  nums.length; i++) {

if(nums[i] == val) {

count++;
for(int j = i; j < nums.length - 1; j++) {

nums[j] = nums[j+1];
}
i--; //所有元素往前移了，我们遍历索引也需要对应进行前一
}
}
return nums.length - count;
}
}

``````

``````class Solution {

public int removeElement(int[] nums, int val) {

int index = 0;
for(int i = 0; i <  nums.length; i++) {

if(nums[i] != val) {

nums[index] = nums[i];
index++;
}
}
return index;
}
}
``````