Array Introduction

What is

An array in Java is an object containing a fixed number of values of the same type. We can have both primitive array and object arrays.

Fixed Length

Once an array is defined, the length will not be able to change.

int[] arr = new int[]{1,2,3}// implicit length declaration of 3
int[] arr = new int[3]; // explicit length declaration

Primitive Array

/*
* Primitive array creation,
* the elements are of primitive datatype.
* so it does not have any methods,
* so arr[0].compareTo(arr[1]) is syntactically wrong
*
* */
int[] arr_primitive_types = new int[]{1, 2, 3};
//arr_primitive_types[0].compareTo(arr_primitive_types[1]);
// syntactically wrong

Object Array

Arrays Utils Class

Java Standard library offers a convenient utility class java.util.Arrays to deal with arrays.

Subsequence of Array

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

All Subsequences

Given an array A, suppose the length of this array is n, then there is a total 2n 2^n number of subsequences.

Use a binary digit for each element in the array to represent if it is present in a given subsequence, then apparently this binary number can represent all numbers within [0,2n−1][0, 2^n - 1]

Turn this thought into code:

Cascading:

Calculate Running Time(Quiz)

Is Subsequence

Brute Force

Two-Pointers

Subarray

A subarray is a contiguous array of a given array. There are precisely n * (n + 1) / 2 number of subarrays.

All Subarray

Calculate Running Time(Quiz)

Longest Increasing Subarray

Brute Force

(Sliding Window) Two-Pointers

A Summary

  • Calculate all subsequences of a given array takes 2n2^nsubsequence findings, which is called an exponential running time.

  • Calculate all subarrays of a given array takes n∗(n+1)2=12(n2+n)\frac{n*(n+1)} {2} =\frac{1} {2}(n^2 + n) subarray findings, which is called an quadratic running time.

  • You can clearly see the drastically running time difference between these two when nn gets large.

Maximum Product of a Non-Empty Subset of an Array

Last updated

Was this helpful?