My Github address
Notes on data Structures and Algorithms
Notes for geek Time iOS Developer Class
IOS large factory interview high frequency algorithm summary
Summary of iOS interview materials
Data structures and algorithms (a): dynamic array
Dynamic visualization of data structures and algorithms
1. Array
- Arrays are one kind
Sequential storage
The memory addresses of all elements are contiguous.int[] array = new int[] {11.22.33} Copy the code
-
In many programming languages, arrays have the fatal drawback of not being able to change their capacity dynamically.
-
In practice we want the size of the array to change dynamically.
Dynamic Array interface design
- create
ArrayList
Class, createsize
Property to manage the number of elements in an arrayelements
Property to manage access to data. - You can do it with dynamic arrays
Add and delete
Operation.
public class ArrayList<E> {
private int size;
private E[] elements;
// The number of elements
int size(a);
// Whether it is empty
boolean isEmpty(a);
// Whether to contain an element
boolean contains(E element);
// Add the element to the end
void add(E element);
// Return the element corresponding to the index position
E get(int index);
// Set the element at index position
E set(int index, E element);
// Add an element to index
void add(int index, E element);
// Delete the element corresponding to the index position
E remove(int index);
// View the position of the element
int indexOf(E element);
// Clear all elements
void clear(a);
}
Copy the code
Three, the implementation of dynamic array
1. Construction method
- If the array space built is smaller than the default space, the array is built to the default space.
public class ArrayList<E> {
private int size;
private E[] elements;
// Sets the default initialization space for elements
private static final int CAPACITY_DEFAULT = 10;
public ArrayList(int capacity) {
capacity = capacity < CAPACITY_DEFAULT ? CAPACITY_DEFAULT : capacity;
elements = (E[]) new Object[capacity];
}
// Convenience constructor
public ArrayList(a) {
this(CAPACITY_DEFAULT); }}Copy the code
2. Add elements
- Array add elements divided into
Add a new element after the last one
andInsert elements into a position (not the last)
Two cases. - The first case, this one
The index to which the new element needs to be added
Is equal to theNumber of elements in the current array
In the ArrayListsize
Attribute isNumber of elements in the current array
, so it’s adding the new element to the arraysize
In position, and thensize
add1
.
public void add(int index, E element) {
elements[index] = element;
size++;
}
Copy the code
- In the second case, just insert the element after the position
Move back
Can. - Note: You need to move elements from back to front. If you move elements from front to back, element overwrite occurs and an error occurs.
2.1. Array out of bounds
- Add the element, also taking care that the index passed in does not cross bounds, i.e
Can't be less than 0, can't be greater than size
.
private void rangeCheckForAdd(int index) {
if (index < 0|| index > size) { outOfBounds(index); }}Copy the code
2.2. Array expansion
- Because of the array
elements
Maximum capacity only10
, so when the array is full, you need to expand the array. - Because arrays cannot be dynamically expanded, you need to create one
New array
, this array has a larger capacity than the previous array. - Then the elements of the original array are stored in the new array, so that the array is expanded.
private void ensureCapacity(a) {
// Get the current capacity of the array
int oldCapacity = elements.length;
// If the number of elements currently stored is less than the current array capacity, return directly
if (size < oldCapacity) return;
// The size of the new array is 1.5 times that of the original array
int newCapacity = oldCapacity + (oldCapacity >> 1);
// Create a new array
E[] newElements = (E[]) new Object[newCapacity];
// The elements in the original array are stored in the new array
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
// Reference the new array
elements = newElements;
}
Copy the code
- implementation
add
Function, which needs to be evaluated before adding new elementsAn array
andcapacity
.
public void add(int index, E element) {
// Judge out of bounds
rangeCheckForAdd(index);
// Determine capacity expansion
ensureCapacity(size + 1);
for (int i = size; i > index; i--) {
elements[i] = elements[i - 1];
}
elements[index] = element;
size++;
}
Copy the code
- In the end
Add a new element after the last one
, i.e.,Add elements to the tail
Is implemented as follows
public void add(E element) {
add(size, element);
}
Copy the code
3. Delete elements
- To delete an element is essentially to remove it
The element at the specified position
And put the following elementTo move forward
. - As shown below, when the index is deleted
3
Just move the next element forward, and then remove the last element,size
Reduction of1
Can.
3.1 Array out of bounds
- The index passed in when deleting an element must not be out of bounds, that is
Can't be less than 0, can't be greater than or equal to size
So we need to do an index check before deleting an element.
private void outOfBounds(int index) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
}
private void rangeCheck(int index) {
if (index < 0|| index >= size) { outOfBounds(index); }}Copy the code
3.2. Array scaling
- When the elements in the array are deleted, the space left in the array may be large, which causes
Waste of memory
. - So when the element in the array is deleted, we need to do the array
Shrinkage capacity
. - The implementation method is similar to expansion, when the size of the array is less than a certain value, create a new array, and then add the elements of the original array
Store new array
Can.
public void trim(a) {
// Get the capacity of the current array
int capacity = elements.length;
// If the size is greater than or equal to half of the capacity, or the capacity is smaller than the default capacity (10), the value is returned
if (size >= capacity >> 1 || capacity < CAPACITY_DEFAULT) return;
// Calculate new capacity = half of original capacity
int newCapacity = capacity >> 1;
// Create a new array
E[] newElements = (E[]) new Object[newCapacity];
// Store the elements of the original array into the new array
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
// Reference the new array
elements = newElements;
}
Copy the code
- In the end,
remove
The method is implemented as follows
public E remove(int index) {
// Determine whether the index is out of bounds
rangeCheck(index);
// Fetch the element to be deleted
E old = elements[index];
// Move all elements after index forward one bit through the loop
for (int i = index + 1; i < size; i++) {
elements[i - 1] = elements[i];
}
// Remove the last element
elements[--size] = null;
// Determine whether the array needs to be shrunk
trim();
// Return the deleted element
return old;
}
Copy the code
4. Empty the array
- When you empty an array, you set all the elements to
null
Only then can you actually release the object, and thensize
Set to0
.
public void clear(a) {
// Clear the stored data
for (int i = 0; i < size; i++) {
elements[i] = null;
}
// Set size to 0
size = 0;
}
Copy the code
5. Modify elements
- When modifying an element, you only need to place the element in its original position
replace
Drop, also need to pay attention to whether the indexCrossing the line
.
public E set(int index, E element) {
// Determine whether the index is out of bounds
rangeCheck(index);
// Fetch the replaced element
E oldElement = elements[index];
// Replace elements
elements[index] = element;
// Returns the replaced element
return oldElement;
}
Copy the code
6. Query elements
- Query element, only need to specify the index of the element, note whether the index
Crossing the line
Can.
public E get(int index) {
rangeCheck(index);
return elements[index];
}
Copy the code
7. View element positions
- You can loop to find the position of the element in the array.
- Note: If the array can be stored
null
And thenull
Yes cannot be calledequals
Method, so you need to evaluate the element passed in if the element being looked for isnull
, need to be handled separately. - Returns index if element exists, variable otherwise
ELEMENT_ON_FOUND
The value of the.
private static final int ELEMENT_NOT_FOUND = -1;
public int indexOf(E element) {
if (element == null) {
for (int i = 0; i < size; i++) {
if (elements[i] == null) returni; }}else {
for (int i = 0; i < size; i++) {
if (element.equals(elements[i])) returni; }}return ELEMENT_NOT_FOUND;
}
Copy the code
8. Whether to contain an element
- Just by checking whether the index is equal to
ELEMENT_ON_FOUND
Can.
public boolean contains(E element) {
// Check whether the element's index is ELEMENT_ON_FOUND
returnindexOf(element) ! = ELEMENT_ON_FOUND; }Copy the code
9. Number of elements
- The size value is the number of elements.
public int size(a) {
return size;
}
Copy the code
10. Whether the array is empty
- By judging
size
Is the value of0
Can.
public boolean isEmpty(a) {
return size == 0;
}
Copy the code
11. Dynamic array printing
- Can be rewritten
toString
Method, to printArrayList
Element in.
@Override
public String toString(a) {
StringBuilder string = new StringBuilder();
string.append("size = ").append(size).append("[");
for (int i = 0; i < size; i++) {
if(i ! =0) {
string.append(",");
}
string.append(elements[i]);
}
string.append("]");
return string.toString();
}
Copy the code
So far, we have successfully implemented dynamic arrays.
Dynamic array complexity
Can ArrayList be further optimized?
- In an ArrayList, if you want to drop an index
0
The position of the element needs to be indexed0
Everything after that moves one place forward. - If you want to index
0
Location to add elements, also need to index0
And all the elements after that move back one.
- Adds an attribute to the ArrayList that records the position of the first element.
- Remove the index
0
The position of the element, we just need to putfirst
Attribute to1
. - In the index
0
To add an element to thefirst
Attribute to0
.
- If you continue to insert elements, the inserted elements are placed in the index
8
This position and willfirst
Instead of8
. - When retrieving the index
8
On the next element, the index is fetched"
, then get the index0
Element of position.
- If an element is inserted, you can choose to move the first or second half of the data.
- In the index
2
Insert element at99
, you can select the element22
.33
Shift to the left and insert99
Can. capacity
andShrinkage capacity
It can also be optimized.