目录
实现数组
package com.algorithm.array;
/**
* 数组构建
*/
public class ArrayTest {
private int size;
private int[] data;
private int index;
/**
*
* @param size 数组大小构建
*/
public ArrayTest(int size) {
this.size = size;
data = new int[size];
this.index = 0;
}
/**
* @param loc 下标
* @param n 值
*/
public void insert(int loc, int n){
// 检查索引是否越界
if(index ++ < size){
// 增加数据时将数据向后移动
for(int i = size - 1; i > loc; i--){
data[i] = data[i-1];
}
data[loc] = n;
}else{
// 进行扩容
}
}
public void delete(int loc){
if(loc <= size && loc >= 0){
// 删除数据时将数据向前移动
for(int i=loc; i < size; i++){
data[i] = data[i+1];
}
index--;
}
}
public void update(int loc, int n){
data[loc] = n;
}
public int get(int loc){
return data[loc];
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int[] getData() {
return data;
}
public void setData(int[] data) {
this.data = data;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
面试题
统计中国每个年龄都有多少人?假设有14亿人口应该如何计算?
1、 创建一个大小为200的int型数组;
2、 逐行读取数据根据年龄大小放入对应下表的数组当中即可
package com.algorithm.array;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* 统计全国有每个年龄段有多少人
*/
public class AgeStatistics {
public static void main(String[] args) {
int[] age = new int[180];
try {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("D:\\age.txt"), StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
while (true){
String s = bufferedReader.readLine();
if(s == null){
break;
}
int i = Integer.parseInt(s);
age[i]++;
}
} catch (IOException e) {
e.printStackTrace();
}
for (int j : age) {
System.out.println(j);
}
}
}
数组下表为什么从0开始?
数据 data[0] data[1] data[2]
内存地址 10001 10002 10003
计算查找地址 10001+0 10001+1 10002+1
节省查找时间 直接计算出内存地址
10001 + 0 * dataSize
二维数组如何寻址
1 ,2, 3
4, 5, 6
转换为一维数组进行寻址公式 i * n + j
i n维-1(看下述例子描述)
n 标识一维数组长度
j 标识所在列 从0开始
比如查找4 1 * 3 + 0
三维数组如何寻址
1 ,2, 3
4, 5, 6
7, 8, 9
查找9 公式: 2 * 3 + 2
四维数组如何寻址
1 ,2, 3
4, 5, 6
7, 8, 9
10, 11, 12
查找11 公式 3 * 3 + 2
java内存分为两大部分
堆内存 存的是new出来的对象和数组
栈内存 存的是引用变量
数组特性
随机访问
查询时间复杂度 永远都是 O(1)
相比于链表查询效率要高,新增删除效率为O(n)