##############################################
Nums So Far: 21
##############################################
-
What is the difference between array and dynamic array?
-
What is the corresponding built-in data structure of array and dynamic array in your frequently-used language?
-
How to perform basic operations (initialization, data access, modification, iteration, sort, etc) in an array?
-
How to perform basic operations (initialization, data access, modification, iteration, sort, addition, deletion, etc) in a dynamic array?
//Array: public class array{ public static void main(String[] args){ //1. initialize int[] a0 = new int[5]; int[] a1 = {1,2,3}; //2. get length int len = a1.length; //3. access element int elem = a1[1]; //4. iterate for(int i = 0; i < a1.length; i++){ System.out.print(" " + a1[i]); } for(int i : a1) System.out.print(" " + i); //5. modify a1[0] = 4; //6. sort Arrays.sort(a1);
}} //Dynamic array (List) public class dynamicArray{ public static void main(String[] args){ //1. initialize List v0 = new ArrayList<>(); List v1; // v1 == null //2. convert array to a vector Integer[] a = {0,1,2,3,4}; v1 = new ArrayList<>(Arrays.asList(a)); //3. make a copy List v2 = v1; // reference to v1 List v3 = new ArrayList<>(v1); // make copy only //4. access element and get length int len = v1.size(); int elem = v1.get(0); //5. iterate same //6. modify v1.set(2,9); //set(index, value) //7. sort Collections.sort(v1); //8. add new element (c++ push_back) v1.add(-1); //9. delete v1.remove(v1.size() - 1);//remove(index);
}}
#724. Find Pivot Index
lass Solution {
public int pivotIndex(int[] nums) {
int n = nums.length;
int[] sums = new int[n];
for(int i = 0; i < n; i++){
if(i == 0) sums[i] = nums[i];
else sums[i] = sums[i - 1] + nums[i];
}
for(int i = 0; i < n; i++){
if(i == 0){
if(sums[n - 1] - nums[0] == 0) return i;
else continue;
}
if((i == n - 1 && sums[n - 2] == 0) || (sums[i - 1] == sums[n - 1] - sums[i])) return i;
}
return -1;
}
}
#747. Largest Number At Least Twice of Others
class Solution {
public int dominantIndex(int[] nums) {
int n = nums.length;
if(n == 1) return 0;
int max = Integer.MIN_VALUE, secmax = Integer.MIN_VALUE, max_index = -1;
for(int i = 0; i < n; i++)
if(nums[i] >= max){
max_index = i;
max = nums[i];
}
for(int i = 0; i < n; i++)
if(nums[i] >= secmax && nums[i] < max)
secmax = nums[i];
if(max >= 2 * secmax) return max_index;
return -1;
}
}
#66. Plus One
class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for(int i = n - 1; i >= 0; i--){
digits[i] = (++digits[i]) % 10;
if(digits[i] != 0) break;
}
if(digits[0] == 0){
int[] plusone = new int[n + 1];
plusone[0] = 1;
return plusone;
}
return digits;
}
}
#498. Diagonal Traverse
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if(matrix.length == 0 || matrix[0].length == 0) return new int[0];
int m = matrix.length, n = matrix[0].length;
int[] ans = new int[m * n];
boolean topdir = true;
int row = 0, col = 0;
for(int c = 0; c < m * n; c++){
ans[c] = matrix[row][col];
if(topdir){
if(row - 1 >= 0 && col + 1 < n){
row--;
col++;
}
else if(col + 1 >= n){
topdir = false;
row++;
}
else{
topdir = false;
col++;
}
}
else{
if(row + 1 < m && col - 1 >= 0){
row++;
col--;
}
else if(row + 1 >= m){
topdir = true;
col++;
}
else{
topdir = true;
row++;
}
}
}
return ans;
}
}
#54. Spiral Matrix
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<Integer>();
if(matrix.length == 0 || matrix[0].length == 0) return ans;
int top = 0, bottom = matrix.length - 1, right = matrix[0].length - 1, left = 0;
while(top <= bottom && right >= left){
for(int i = left; i <= right; i++) ans.add(matrix[top][i]);
for(int i = top + 1; i <= bottom; i++) ans.add(matrix[i][right]);
if(top != bottom && right != left){
for(int i = right - 1; i >= left; i--) ans.add(matrix[bottom][i]);
for(int i = bottom - 1; i > top; i--) ans.add(matrix[i][left]);
}
bottom--;
top++;
right--;
left++;
}
return ans;
}
}
#118. Pascal's Triangle
class Solution{
public List<List<Integer>> generate(int numRows){
List<List<Integer>> ans = new ArrayList<>();
if(numRows == 0) return ans;
return genLines(numRows, ans);
}
public List<List<Integer>> genLines(int n, List<List<Integer>> res){
int m = res.size();
if(m == n) return res;
List<Integer> line = new ArrayList<>();
if(m == 0) line.add(1);
else{
List<Integer> lastLine = res.get(m - 1);
for(int i = 0; i < lastLine.size() + 1; i++){
if(i == 0 || i == lastLine.size()) line.add(1);
else line.add(lastLine.get(i) + lastLine.get(i - 1));
}
}
res.add(line);
return genLines(n, res);
}
}
In Java, String is immutable, which means every time when you do concatenation, it reserves enough space for the following String and copy the original ones into new.
The way to make it mutable in Java is:
- use String.toCharArray
- use Java.StringBuilder(with same operation of concatenation, it takes O(n) instead of O(n^2) comparing to String)
#67. Add Binary
1) my slow version
class Solution {
public String addBinary(String a, String b) {
StringBuilder ans = new StringBuilder();
int len1 = a.length(), len2 = b.length();
int i = len1 - 1, j = len2 - 1, carry = 0;
while(i >= 0 && j >= 0){
int cur = Character.getNumericValue(a.charAt(i--)) + Character.getNumericValue(b.charAt(j--)) + carry;
if(cur >= 2){
carry = 1;
ans.insert(0, Integer.toString(cur - 2));
}
else{
carry = 0;
ans.insert(0, Integer.toString(cur));
}
}
while(i >= 0){
if(carry == 1){
int cur = Character.getNumericValue(a.charAt(i--)) + carry;
if(cur >= 2){
carry = 1;
ans.insert(0, Integer.toString(cur - 2));
}
else{
carry = 0;
ans.insert(0, Integer.toString(cur));
}
}
else ans.insert(0, a.charAt(i--) + "");
}
while(j >= 0){
if(carry == 1){
int cur = Character.getNumericValue(b.charAt(j--)) + carry;
if(cur >= 2){
carry = 1;
ans.insert(0, Integer.toString(cur - 2));
}
else{
carry = 0;
ans.insert(0, Integer.toString(cur));
}
}
else ans.insert(0, b.charAt(j--) + "");
}
if(carry == 1) ans.insert(0, Integer.toString(1));
return ans.toString();
}
}
#28. Implement strStr()
class Solution {
public int strStr(String haystack, String needle) {
int window_size = needle.length(), hay_size = haystack.length();
if(window_size == 0) return 0;
if(window_size > hay_size) return -1;
int i = 0, j = i + window_size;
while(j <= hay_size){
if(haystack.substring(i, j).equals(needle)) return i;
i++;
j++;
}
return -1;
}
}
#14. Longest Common Prefix improved!
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0) return "";
if(strs.length == 1) return strs[0];
int shortest_index = 0, length = strs[0].length();
for(int i = 1; i < strs.length; i++){
if(strs[i].length() < strs[shortest_index].length()) shortest_index = i;
}
StringBuilder prefix = new StringBuilder();
prefix.append(strs[shortest_index]);
for(int i = 0; i < strs.length; i++){
prefix = edit_prefix(prefix, strs[i]);
if(prefix.length() == 0) return "";
}
return prefix.toString();
}
public StringBuilder edit_prefix(StringBuilder prefix, String cur){
while(prefix.length() > 0){
if(cur.substring(0, prefix.length()).equals(prefix.toString())) return prefix;
else prefix.delete(prefix.length() - 1, prefix.length());
}
return prefix;
}
}
#344. Reverse String
class Solution {
public void reverseString(char[] s) {
int n = s.length, i = 0, j = n - 1;
if(n == 0 || n == 1) return;
while(i < j){
char cur = s[i];
s[i++] = s[j];
s[j--] = cur;
}
}
}
or recursively:
class Solution {
public void reverseString(char[] s) {
reverse(0, s.length - 1, s);
}
public void reverse(int i, int j, char[] s){
if(i >= j) return;
char cur = s[i];
s[i++] = s[j];
s[j--] = cur;
reverse(i, j, s);
}
}
#561. Array Partition I
class Solution {
public int arrayPairSum(int[] nums) {
int n = nums.length, i = 0, sum = 0;
if(n == 0) return 0;
Arrays.sort(nums);
while(i < n - 1){
sum += nums[i];
i += 2;
}
return sum;
}
}
#167. Two Sum II - Input array is sorted
class Solution {
public int[] twoSum(int[] numbers, int target) {
int i = 0, j = numbers.length - 1;
while(i < j){
int l = numbers[i], r = numbers[j];
if(l + r == target) return new int[] {i + 1, j + 1};
else if(l + r > target) j--;
else i++;
}
throw new IllegalArgumentException();
}
}
#27. Remove Element
class Solution {
public int removeElement(int[] nums, int val) {
int n = nums.length, i = 0, j = 0;
while(j < n){
if(nums[j] != val) swap(nums, i++, j);
j++;
}
return i;
}
public void swap(int[] arr, int i, int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
#485. Max Consecutive Ones
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0, n = nums.length, i = 0, j = 0;
while(j < n){
if(nums[j] != 1){
max = Math.max(max, j - i);
j++;
i = j;
}
else j++;
}
return Math.max(max, j - i);
}
}
#209. Minimum Size Subarray Sum
class Solution{
public int minSubArrayLen(int s, int[] nums){
int left = 0, n = nums.length, sum = 0, min = Integer.MAX_VALUE;
int right = 0;
while(right < n){
sum += nums[right];
while(sum >= s){
min = Math.min(min, right - left + 1);
sum -= nums[left++];
}
right++;
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}
#189. Rotate Array
class Solution {
public void rotate(int[] nums, int k) {
if(nums.length <= k) k %= nums.length;
rotateNStep(nums, k);
}
public void rotateNStep(int[] nums, int k){
flipSub(nums, 0, nums.length - 1);
flipSub(nums, 0, k - 1);
flipSub(nums, k, nums.length - 1);
}
public void flipSub(int[] nums, int start, int end){
while(start < end){
swap(nums, start++, end--);
}
}
public void swap(int[] nums, int i, int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
#119. Pascal's Triangle II
class Solution{
public List<Integer> getRow(int rowIndex){
List<Integer> ans = new ArrayList<>();
ans.add(1);
if(rowIndex == 0) return ans;
return curRow(rowIndex, 0, ans);
}
public List<Integer> curRow(int exp, int cur, List<Integer> lastRow){
if(exp == cur) return lastRow;
else if(exp < cur) throw new IllegalArgumentException();
else{
List<Integer> generated = new ArrayList<>();
for(int i = 0; i <= lastRow.size(); i++){
if(i == 0 || i == lastRow.size()) generated.add(1);
else generated.add(lastRow.get(i) + lastRow.get(i - 1));
}
return curRow(exp, cur + 1, generated);
}
}
}
#151. Reverse Words in a String
class Solution {
public String reverseWords(String s) {
return reverseByWord(stripMultiSpaces(s.trim()));
}
public String reverseByWord(String s){
StringBuilder sb = new StringBuilder();
int n = s.length(), i = n - 1, j = n - 1;
while(i >= 0){
if(s.charAt(i) != ' ') i--;
else{
sb.append(s.substring(i + 1, j + 1));
sb.append(" ");
i--;
j = i;
}
}
if(j != i) sb.append(s.substring(i + 1, j + 1));
return sb.toString();
}
public String stripMultiSpaces(String str){
StringBuilder sb = new StringBuilder();
int n = str.length(), i = 0, j = 0;
while(j < n){
if(str.charAt(j) != ' '){
if(j != i){
sb.append(' ');
}
sb.append(str.charAt(j));
j++;
i = j;
}
else j++;
}
return sb.toString();
}
}
#557. Reverse Words in a String III
class Solution {
public String reverseWords(String s) {
StringBuilder ans = new StringBuilder();
String words[] = s.split(" ");
for(String word : words){
ans.append(reverse_word(word) + " ");
}
return ans.toString().trim();
}
public String reverse_word(String word){
char[] chars = word.toCharArray();
int n = word.length(), i = 0, j = n - 1;
while(i < j){
char tmp = chars[i];
chars[i++] = chars[j];
chars[j--] = tmp;
}
return new String(chars);
}
}
#26. Remove Duplicates from Sorted Array
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length, i = 0, j = 1;
if(n == 0 || n == 1) return n;
while(j < n){
if(nums[j] != nums[i]) swap(nums, ++i, j++);
else j++;
}
return i + 1;
}
public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
#283. Move Zeroes
class Solution {
public void moveZeroes(int[] nums) {
int n = nums.length, i = 0, j = 0;
if(n == 0 || n == 1) return;
while(j < n){
if(nums[j] != 0) swap(nums, i++, j++);
else j++;
}
}
public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}