Programmer growth path (Day 28)

Posted by dmcke5 on Mon, 21 Feb 2022 03:22:23 +0100

catalogue

Learning objectives:

Learning content:

Object oriented encapsulation features:

Use steps:

Advantages of encapsulation:

Class definition specification: (JavaBean specification)

Scope of local variables and member variables:

Static attribute, static method, static code block:

Definition:

Difference:

Example:

Static code block supplement:

effect:

Static code blocks cannot appear in any method body:

Static code blocks cannot access normal variables:

Execution sequence:

Precautions for using static:

Static and non static relationships in parent-child classes:

Object oriented inheritance features:

Concepts involved in inheritance

Class and inheritance

(1) Classification of classes

(2) Inheritance law of class

(3) Constraints followed by inheritance laws

Modifiers and inheritance

Code

Advantages and disadvantages of inheritance

Details of construction method in inheritance:

        1. You can use super's parametric construction method:

        2. Use this to call your own parameterized constructor:

Object oriented polymorphism:

Form

Concept

Recognition skills

Use premise

Supplementary examples

java uses ellipsis instead of multiple parameters (parameter type... Parameter name) java uses ellipsis instead of multiple parameters (parameter type... Parameter name)

Abstract methods and abstract classes

Definition:

Usage

Use case

Interface

Concept

The difference between interface and abstract class

default method

LintCode brush questions:

·Lemonade change

· maximum subarray

·K-diff pair in array

· maximum subarray III

· complete square

·Maximum palindrome product

·Music combination

·Sum of left leaves​​

·Judgment repetition

·John's business

Learning emotion:

Learning output:

Learning objectives:

  • Object oriented encapsulation
  • Scope of local variables and member variables
  • Static attribute, static method, static code block
  • Object oriented inheritance
  • Details of construction methods in inheritance
  • Object oriented polymorphism
  • Abstract methods and abstract classes
  • Interface

Learning content:

Object oriented encapsulation features:

Some information of the class is hidden inside the class, which is not allowed to be directly accessed by external programs. Instead, the method provided by the class is used to realize the operation and access of hidden information, hide as many things as possible, and only provide convenient interfaces to the outside.

Use steps:

1. Attribute privatization: change the access right modifier of the attribute to private

2. Provide public operation and access methods (getter and setter methods): create two methods for each attribute, one is setXXX to set the value, and the other is getXXX to read the value

3. Add reasonable judgment and handling in the operation and access methods as needed

Advantages of encapsulation:

1. It is convenient for users to use the system correctly and prevent wrong modification of attributes. (improves the security and robustness of the program)

2. Contribute to loose coupling (low coupling) between systems and improve system independence

3. Improve software reusability (relatively independent whole, high cohesion)

Class definition specification: (JavaBean specification)

  • Property privatization
  • Provide common operation and access methods
  • Write parameterless construction method
  • Implement Serializable interface

PS: many classes can be written in a java source code file (. Java), but only one class can be modified by public, and the name of this class is consistent with the file name

Suggestion: there is no special case. Write a class in one source file

Scope of local variables and member variables:

Member variables: (1) variables defined in classes and outside methods.

(2) member variables can not be explicitly initialized, and they can be set by the system as default values;

(3) the member variable is stored in heap memory after its class is instantiated

Local variables: (1) variables defined inside the method body.

(2) the local variable has no default value, so the initial assignment must be set.

(3) local variables exist in the stack memory space when the local method is called.  

Static attribute, static method, static code block:

Definition:

Attributes and methods modified with static modifiers are called static attributes and static methods

Static code blocks can only be written outside the methods in the class, not in the methods. They will take precedence over the loading of various code blocks and construction methods with the loading of the class, and will only be loaded once. If multiple static code blocks appear, they will be loaded in writing order

Difference:

1. Different storage locations in memory: all static modified attributes and methods are stored in the method area of memory, while non static ones are stored in heap memory
2. The timing of occurrence is different: static attributes and methods exist before the object is created, while non static ones need to exist only after the object is created
3. Static attributes are common to the whole class
4. The life cycle is different. Static classes are destroyed after they disappear, and non static objects are destroyed after they are destroyed
5. Usage: static can be accessed directly through the class name, and non static can only be accessed through the object

Example:

public class StaticTest {
	public static void main(String[] args) {
	test t  =new test();
	test a = new test();
	System.out.println(t.a);
	System.out.println(test.c);
	//test.eat() eat is a normal method. Do you want to be called directly? Can only be called by the object like the next line!
	t.eat();   
	//run is a static method with high permissions. It can be called by object or class name
	t.run();    
	test.run();
	}
	static class test{
		String a ="I'm a normal variable a,Can only be called by objects";
		static String c = "I'm a static variable c,Can be called by object or class name";
		//Non static code blocks are executed every time an object is created
		{
			System.out.println("I am a non static code block. I can only create objects. I will execute them once! If I am created twice, execute twice!");
		}
		//Static code blocks can only be executed once
		static{
			System.out.println("I'm a static code block. I only execute it once");
		}
		//Normal methods can only be called by objects
		public void eat(){
			System.out.println("I am eat Method is an ordinary method. I have low permissions and can only be called by objects!");
		}
		//Static methods can be called by object and class names
		public static void run(){
			System.out.println("I am run method,It is a static method with high permissions. It can be called directly by class name or object");
		}	
	}
}
/*(1)Non static property: Property (i.e. common property) can only be called by object 
           Static attribute: can be called directly by object or class name. (more authority)
  (2)Non static methods (i.e. methods without static modifier): can only be called by objects
           Static method: can be called directly by object or class name. (more authority)
  (3)Non static code block: executed every time an object is created
           Static code block: execute only once when the class is loaded into memory! No longer executes the class when it is called later!*/

Output:

I'm a static code block. I only execute it once
I am a non static code block. I can only create objects. I will execute them once! If I am created twice, execute twice!
I am a non static code block. I can only create objects. I will execute them once! If I am created twice, execute twice!
I am an ordinary variable a, which can only be called by objects
I am a static variable c, which can be called by object or class name
I am an eat method, an ordinary method. I have low permissions and can only be called by objects!
I am a run method, a static method with high permissions. I can be called directly by the class name or by an object
I am a run method, a static method with high permissions. I can be called directly by the class name or by an object

Static code block supplement:

effect:

In general, some code needs to be executed when the project is started. At this time, static code blocks are required. For example, a project needs to load configuration files or initialize contents when it is started.

Static code blocks cannot appear in any method body:

For ordinary methods: ordinary methods need to load the class new to create an instantiated object. Only by running this object can the code block be run, while static methods run with the class loading.
For static methods: static methods are also loaded when the class is loaded, but they can be accessed only when the class name or object name is required. Compared with static code blocks, static methods run passively, while static code blocks run actively.

Static code blocks cannot access normal variables:

Ordinary variables can only be called through objects, so ordinary variables cannot be placed in static code blocks.

Execution sequence:

Static code block > construction code block > constructor > normal code block

Precautions for using static:

  • Methods with static modifiers can only access static properties
  • Non static methods can access both static and non static properties
  • Non static methods cannot define static variables
  • Static methods cannot use this keyword
  • Static methods cannot call non static methods, and vice versa

Static and non static relationships in parent-child classes:

  • For non static attributes, a subclass can inherit the non static attributes of the parent class. However, when the parent and child classes have the same non static attributes, the subclass will not override and overwrite the non static attributes of the parent class, but hide the non static attributes of the parent class
  • For non static methods, subclasses can inherit and override the non static methods of the parent class
  • For static attributes, subclasses can inherit the static attributes of the parent class, but how to be the same as non static attributes will be hidden
  • For static methods, a subclass can inherit the static method of the parent class, but cannot override the static method. When the same name is used, the parent class will be hidden

Note: static attributes, static methods and non static attributes can be inherited and hidden, but they cannot be overridden,
Non static methods can be overridden and inherited

Object oriented inheritance features:

Concepts involved in inheritance

  • Understanding: the mechanism for subclasses to automatically share parent class data and methods is the relationship between classes, which is called inheritance. Inheritance is to generate a new type on the basis of an existing type by adding new methods or redefining existing methods (i.e. overriding).
  • Inheritance: the inherited class is called the parent class (superclass), and the class that inherits the parent class is called the child class (derived class). Inheritance refers to that one object directly uses the properties and methods of another object, and code reuse can be realized through inheritance.
  • Super keyword: you can access the members of the parent class through the super keyword. It is used to refer to the parent class of the current object. Use super to call the properties in the parent class, call the methods of the parent class, and call the construction methods in the parent class. Super indicates the default reference of the parent object. If the child class wants to call the instance method whose parent class is overridden, Super can be used as the caller to call the instance method whose parent class is overridden, super can be used to call the parent class method, and super can be used to call the constructor of the parent class.
  • Method override: Method override is also called rewriting;
    • The reason is as like as two peas appear in the parent class, when the method is not suitable for subclasses, the subclass has the same parent method called the parent class method: super. Method name (argument); Principles to be followed when overwriting methods (together, two small, one large): (together): method signatures must be the same; (two small): the return value type of the subclass method is smaller or equal than that of the parent method; The exception thrown by the subclass method declaration should be smaller or equal (one large) than that thrown by the parent method declaration: the access permission of the subclass method should be larger or equal than that of the parent method.
  • Subclass object instantiation process:
    • Instantiation of subclass objects: subclass objects must first call the construction method in the parent class before instantiation, and then call their own construction method; When a subclass instantiates, it will first let its parent class instantiate (call the construction method of the parent class), and then the subclass instantiates itself;
    • The subclass accesses the parent class; Subclasses cannot directly access the private members of the parent class, but subclasses can call non private methods in the parent class to indirectly access the private members of the parent class.

Class and inheritance

(1) Classification of classes

  • Class: a class that uses class definition and does not contain abstract methods.
  • Abstract class: a class defined by abstract class. It can contain or not contain abstract methods.
  • Interface: a class defined using interface.

(2) Inheritance law of class

  • Classes can inherit classes, abstract classes, and interfaces.
  • Abstract classes can inherit classes, abstract classes and interfaces.
  • Interfaces can only inherit interfaces.

(3) Constraints followed by inheritance laws

  • Class and abstract class can only inherit at most one class or at most one abstract class, and the two cases are mutually exclusive, that is, they either inherit a class or an abstract class.
  • When inheriting interfaces, classes, abstract classes and interfaces are not subject to quantitative constraints. Theoretically, they can inherit unlimited interfaces. For a class, it must implement all methods defined in all interfaces it inherits.
  • When an abstract class inherits an abstract class or implements an interface, it can partially, completely or completely not implement the abstract method of the parent abstract class or the interface defined in the parent interface.
  • When a class inherits an abstract class or implements an interface, it must implement all abstract methods of the parent abstract class or all interfaces defined in the parent interface.

Modifiers and inheritance

(1) Relationship between class member access modifier and access capability:

typeprivateNo modificationprotectedpublic
Same classAccessibleAccessibleAccessibleAccessible
Same package of neutronsInaccessibleAccessibleAccessibleAccessible
Non subclasses in the same packageInaccessibleAccessibleAccessibleAccessible
Subclasses in different packagesInaccessibleInaccessibleAccessibleAccessible
Non subclasses in different packagesInaccessibleInaccessibleInaccessibleAccessible


(2) Subclasses cannot inherit member variables and methods with private access in the parent class, nor can they inherit the constructor of the parent class. Subclasses can override the methods of the parent class and name member variables with the same name as the parent class.

Code

public class Demo {
    public static void main(String[] args) {
        Apple apple =new Apple(10);
    }
}
public class Fruits {
    private int num;
    public Fruits(){
        System.out.println("This is Fruits Nonparametric construction method of class");
    }
    public Fruits(int num){
        System.out.println("This is Fruits Class with parameters"+"Quantity:"+num);
    }
}
public class Apple extends Fruits{
    Apple(){
        System.out.println("This is Apple Nonparametric construction method of class");
    }
    Apple(int num){
        super(num);
        System.out.println("This is Apple Class with parameters");
    }
}
//
This is Fruits The number of construction methods with parameters of class is: 10
 This is Apple Class with parameters

Advantages and disadvantages of inheritance

  • Advantages: it improves the reusability of code; It makes the relationship between classes and provides the premise of polymorphism.
  • Disadvantages: it improves the coupling between classes. A high degree of coupling will cause the closer the connection between codes and the worse the independence of codes.

Details of construction method in inheritance:

  • A: Case demonstration
    • The parent class has no parameter free construction method. What about the child class?
  • B: Precautions
    • super(...) or this(...) Must appear on the first statement of the constructor

        1. You can use super's parametric construction method:

package Demo2;

import Demo2.Son;

public class Demo2 {
    public static void main(String[] args){
        Son s1 = new Son();
        System.out.println(s1.getName() + "---" + s1.getAge());
        System.out.println("----------");
        Son s2 = new Son("Zhang San", 23);
        System.out.println(s2.getName() + "---" + s2.getAge());
    }
}

public class Father{
    private String name;        
    private int age;            

    /*
    public Father(){            //Empty parameter structure
        System.out.println("Father Empty parameter structure "");
    }
    */

    public Father(String name, int age){    //Parametric structure
        this.name = name;
        this.age = age;
        System.out.println("Father Parametric structure");
    }

    public void setName(String name){      
        this.name = name;
    }

    public String getName(){                
        return name;
    }

    public void setAge(int age){           
        this.age = age;
    }

    public int getAge(){                   
        return age;
    }
}

public class Son extends Father{
    public Son(){
        super("Li Si",24);                            
        System.out.println("Son Empty parameter structure");
    }

    public Son(String name, int age){
        super(name, age);
        System.out.println("Son Parametric structure");
    }
}

        2. Use this to call your own parameterized constructor:

package Demo2;

import Demo2.Son;

public class Demo2 {
    public static void main(String[] args){
        Son s1 = new Son();
        System.out.println(s1.getName() + "---" + s1.getAge());
        System.out.println("----------");
        Son s2 = new Son("Zhang San", 23);
        System.out.println(s2.getName() + "---" + s2.getAge());
    }
}

public class Father{
    private String name;        
    private int age;            

    /*
    public Father(){            //Empty parameter structure
        System.out.println("Father Empty parameter structure "");
    }
    */

    public Father(String name, int age){    //Parametric structure
        this.name = name;
        this.age = age;
        System.out.println("Father Parametric structure");
    }

    public void setName(String name){      
        this.name = name;
    }

    public String getName(){                
        return name;
    }

    public void setAge(int age){           
        this.age = age;
    }

    public int getAge(){                   
        return age;
    }
}

class Son extends Father{
    public Son(){
        //this and super are parallel, and only one can exist
        this("Li Si", 24);             //Call the constructor in this class
        System.out.println("Son Empty parameter structure");
    }

    public Son(String name, int age){
        super(name, age);
        System.out.println("Son Parametric structure");
    }
}

Object oriented polymorphism:

Form

Parent type object name = new subclass constructor; Interface object name = new implementation class constructor;

Range of parent type > range of child type.

Concept

When an object of the same type performs the same behavior, it will show different behavior characteristics in different states.

Recognition skills

For method calling: compile and run on the left and right. Call variables: compile and run on the left.

Use premise

(1) There must be an inheritance or implementation relationship. (2) there must be a variable of parent type that references an object of subclass type. (3) method rewriting is required.

public class Main {
    public static void main(String[] args) {
        Person p = new Student();
        p.run(); // Student.run
    }
}

class Person {
    public void run() {
        System.out.println("Person.run");
    }
}

class Student extends Person {
    @Override
    public void run() {
        System.out.println("Student.run");
    }
}

Supplementary examples

java uses ellipsis instead of multiple parameters (parameter type... Parameter name)java uses ellipsis instead of multiple parameters (parameter type... Parameter name)

public class Main {
    public static void main(String[] args) {
        // Tax is calculated for a small partner with ordinary income, wage income and special allowance of the State Council:
        Income[] incomes = new Income[] {
            new Income(3000),
            new Salary(7500),
            new StateCouncilSpecialAllowance(15000)
        };
        System.out.println(totalTax(incomes));
    }
    // Income... incomes == Income[] incomes
    public static double totalTax(Income... incomes) {
        double total = 0;
        for (Income income: incomes) {
            total = total + income.getTax();
        }
        return total;
    }
}

class Income {
    protected double income;

    public Income(double income) {
        this.income = income;
    }

    public double getTax() {
        return income * 0.1; // Tax rate 10%
    }
}

class Salary extends Income {
    public Salary(double income) {
        super(income);
    }

    @Override
    public double getTax() {
        if (income <= 5000) {
            return 0;
        }
        return (income - 5000) * 0.2;
    }
}

class StateCouncilSpecialAllowance extends Income {
    public StateCouncilSpecialAllowance(double income) {
        super(income);
    }

    @Override
    public double getTax() {
        return 0;
    }
}

Observe the totalTax() method: using polymorphism, the totalTax() method only needs to deal with Income. It doesn't need to know the existence of Salary and StateCouncil special allowance to correctly calculate the total tax. If we want to add a new kind of royalty Income, we only need to derive from Income and correctly override the getTax() method. Pass the new type into totalTax() without any code modification.

It can be seen that polymorphism has a very powerful function, which is to allow adding more types of subclasses to realize function expansion without modifying the code based on the parent class.

Abstract methods and abstract classes

Definition:

If a class defines a method but does not specifically execute code, the method is an abstract method, which is decorated with abstract. Because the abstract method cannot be executed, this class must also be declared as an abstract class. A class decorated with abstract is an abstract class. We cannot instantiate an abstract class.

Because the abstract class itself is designed to be inherited only, the abstract class can force its subclass to implement its defined abstract methods, otherwise the compilation will report an error. Therefore, the abstract method is actually equivalent to defining the "specification". For example, if the Person class defines the abstract method run(), the run() method must be overridden when implementing the subclass Student:

public class Main {
    public static void main(String[] args) {
        Person p = new Student();
        p.run();
    }
}

abstract class Person {
    public abstract void run();
}

class Student extends Person {
    @Override
    public void run() {
        System.out.println("Student.run");
    }
}

Usage

1. new abstract class objects cannot be created directly.
2. A subclass must be used to inherit the abstract parent class;
3. The subclass must override all abstract methods in the parent class
Override (Implementation): remove the abstract keyword of the abstract method, and then add the contents of the method body braces
4. Create subclass objects and use

PS:

  1. Abstract classes cannot create objects
  2. Abstract classes can have construction methods
  3. Abstract classes do not necessarily contain abstract methods
  4. Subclasses of abstract classes must override all abstract methods

Use case

public class Demo {
    public static void main(String[] args) {
        // Tax is calculated for a small partner with salary income and special allowance of the State Council:
        Income[] incomes = new Income[] {
                new SalaryIncome(7500),
                new RoyaltyIncome(15000)
        };
        System.out.println(totalTax(incomes));
    }

    public static double totalTax(Income[] incomes) {
        double total = 0;
        for (Income income: incomes) {
            total = total + income.getTax();
        }
        return total;
    }
}
public abstract class Income {
    protected double income;
    public Income(double income){
        this.income=income;
    }
    public abstract double getTax();
}

public class SalaryIncome extends Income{
    public SalaryIncome(double income) {
        super(income);
    }
    @Override
    public double getTax(){
        if (income <= 5000) {
            return 0;
        }
        return (income - 5000) * 0.2;
    }
}
public class RoyaltyIncome extends Income{
    public RoyaltyIncome(double income) {
        super(income);
    }
    @Override
    public double getTax(){
        return income*0.2;
    }

}

Interface

Concept

Interface can be understood as a special class, which is composed of global constants and public abstract methods. Interface is a means to solve the problem that Java cannot use multi inheritance, but interface plays a more important role in setting standards in practice. Or we can directly understand the interface as a 100% abstract class, that is, all the methods in the interface must be abstract methods.

The difference between interface and abstract class

abstract classinterface
Construction methodThere are construction methods for subclass instantiation.No construction method
Member variableIt can be a variable or a constant.

Can only be constants.

Default modifier: public static final

Member methodIt can be abstract or non abstract.jdk1.7 can only be abstract. Default modifier: public abstract (recommended: Please always give the default modifier manually)
jdk1.8. You can write specific methods starting with default and static
inheritOnly one class can be extendedMultiple interface s can be implemented

default method

public class Main {
    public static void main(String[] args) {
        Person p = new Student("Xiao Ming");
        p.run();
    }
}

interface Person {
    String getName();
    default void run() {
        System.out.println(getName() + " run");
    }
}

class Student implements Person {
    private String name;

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

The implementation class does not have to override the default method. The purpose of the default method is that when we need to add a method to the interface, it will involve modifying all subclasses. If you add a default method, you don't have to modify all the subclasses. You just need to override the new method where you need to override it. The default method is different from the ordinary method of the abstract class. Because the interface has no field, the default method cannot access the field, while the ordinary method of the abstract class can access the instance field.

LintCode brush questions:

·Lemonade change

Define two int variables, which are used to put five yuan and ten yuan. Five yuan entry is a five variable. Five variable is required when ten yuan variable enters. Five variable -- is required when 20 yuan variable enters. Judge whether ten yuan variable is 0. When ten is 0, five-3 is required. When ten is not 0, ten -- and five -- only need to finally judge whether five value is negative.

import java.util.List;

public class Solution {
    public boolean lemonadeChange(List<Integer> bills) {
        int five = 0, ten = 0;
        for (int i : bills) {
            if (i == 5) {
                five++;
            }
            if (i == 10) {
                ten++;
                five--;
            }
            if (i == 20) {
                if (ten == 0) {
                    five -= 3;
                } else {
                    five--;
                    ten--;
                }
            }
        }
        if (ten < 0 || five < 0)
            return false;
        else
            return true;
    }
}

· maximum subarray

Create an array according to the size of K, traverse the array according to A, and record the subscript value where it is large.

public class Solution {
    
    public int[] largestSubarray(int[] A, int K) {

        int[] res = new int[K];
        int start = 0;
        for (int i = 0; i <= A.length - K; i++) {
            for(int j = 0; j < K; j++) {
                if(A[i + j] > A[start + j]) {
                    start = i;
                    break;
                }
                else if (A[i + j] < A[start + j]){
                    break;
                }
            }
        }
        for(int i = 0; i < K; i++) {
            res[i] = A[start + i];
        }
        return res;
    }
}

·K-diff pair in array

1. Sort the array first, and then establish a double pointer. Each time, traverse all the elements behind the first pointer. When the elements behind the first pointer or the second pointer are the same as the elements pointed to by the pointer, move the pointer back one bit. When the two pointers point to the same, move the following pointer one bit. When the latter bit exceeds the range, jump out of the loop, because sorting in order, Therefore, when the difference between two pointers exceeds K, the next pointer must be larger than K. therefore, when the difference is less than k, the second pointer will move backward. When it is equal to K, it can be marked with + +.

import java.util.Arrays;

public class Solution {

    public int findPairs(int[] nums, int k) {
        Arrays.sort(nums);
        int temp = 0;
        for (int i = 0, j = 0; i < nums.length; i++) {
            if (i == j) j++;
            while (i + 1 < nums.length && nums[i + 1] == nums[i]) i++;
            while (j + 1 < nums.length && nums[j + 1] == nums[j]) j++;
            while (j < nums.length && Math.abs(nums[j] - nums[i]) < k) j++;
            if (j >= nums.length) break;
            if (Math.abs(nums[j] - nums[i]) == k) {
                temp++;
                j++;
            }
        }
        return temp;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = new int[]{3,1,4,1,5};
        System.out.println(solution.findPairs(arr,2));
    }
}

· maximum subarray III

In dynamic programming, prepare to divide the array into k groups, and establish two two-dimensional arrays with a length 1 larger than length and K. then you need to know that the global array represents the global optimal solution (not including its own elements), and the local optimal solution (must include the current elements). i represents how many numbers are taken, J represents how many groups are divided, and when i and j are equal, This element is directly added to the following table element whose fetching and grouping are less than 1. When i and j are not equal, the local optimal solution needs to compare the size of the same number of groups with one less element in the global and one less group and one less local element, and then add the current element. The global optimal solution only needs to compare the global and take less of the same group of current elements and the size of the current local optimal solution.

public class Solution {
    public int maxSubArray(int[] nums, int k) {
        int n = nums.length;
        if (n < k){
            return 0;
        }
        int[][] local = new int[n + 1][k + 1];
        int[][] global = new int[n + 1][k + 1];
        for (int i = 1; i <= n; i++){
            for (int j = Math.min(i,k); j > 0; j--){
                if(i == j){
                    local[i][j] = local[i - 1][j - 1] + nums[i - 1];
                    global[i][j] = global[i - 1][j - 1] + nums[i - 1];
                }
                else{
                    local[i][j] = Math.max(local[i - 1][j], global[i - 1][j - 1]) + nums[i - 1];
                    global[i][j] = Math.max(global[i - 1][j], local[i][j]);
                }
            }
        }
        return global[n][k];
    }
}

· complete square

After the square is derived, it can be directly converted to int type, and then judge whether the square of int value is equal to num

public class Solution {
    public boolean isPerfectSquare(int num) {
        int a = (int)Math.sqrt(num);
        
        if (a*a==num){
            return true;}
        else{
            return false;
        }
    }
}

·Maximum palindrome product

Find the maximum n digits and write a method to make the palindrome number, because n bits × The number of palindromes formed by N bits is 2n bits, so just start from the current maximum number of N bits, form it into the number of palindromes, and then traverse from the maximum to find a place that can be divided.

public class Solution {
    public int largestPalindrome(int n){
        if (n==1)
            return 9;
        long maxNumber = (long) Math.pow(10,n)-1;
        long minNumber =(long) Math.pow(10,n-1);
        long maxlimit =maxNumber*maxNumber;
        long temp =maxNumber;
        while (true){
            long firstHalf=palindrome(temp--);
            if (firstHalf>maxlimit)
                continue;
            for (long i = maxNumber;i>=minNumber;i--){
                if (firstHalf/i>maxNumber)
                    break;
                if (firstHalf%i==0){
                    System.out.println(firstHalf);
                    return (int) (firstHalf%1337);
                }
            }
        }
    }

    public long palindrome(long firstHalf) {
        StringBuffer stringBuffer = new StringBuffer(Long.toString(firstHalf));
        String str = firstHalf+stringBuffer.reverse().toString();
        return Long.parseLong(str);
    }
}

·Music combination

It will be too slow to traverse with the for loop, so you can directly create a one-dimensional array to play music within 60. You only need to get whether 60 music has it or not, so you can put temp + +;

public class Solution {
    public long musicPairs(int[] musics) {
        int [] arr =new int[60];
        long temp =0;
        for (int music:musics){
            if (music%60==0){
                temp+=arr[0];
                arr[0]++;
                continue;
            }
            temp+=arr[60-music];
            arr[music]++;
        }
        return temp;
    }
}

·Sum of left leaves

First put the root node into the, and determine whether the left and right child nodes are empty. When they are not empty

public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        int sum = 0;
        if (root == null) {
            return 0;
        }
        if (root.left != null) {
            TreeNode left = root.left;
            if (left.left == null && left.right == null) {
                sum += left.val;
            } else
                sum += sumOfLeftLeaves(left);
        }
        if (root.right!=null){
            TreeNode right= root.right;
            sum+=sumOfLeftLeaves(right);
        }
        return sum;
    }
}

·Judgment repetition

Put the array into hashset and compare the length

import java.util.HashSet;
import java.util.LinkedHashSet;

public class Solution {

    public boolean isUnique(int[] arr) {
        HashSet set =new LinkedHashSet();
        for (int i:arr){
            set.add(i);
        }
        if (set.size()==arr.length){
            return true;
        }else 
            return false;
    }
}

·John's business

public class Solution {
    /**
     * @param A: The prices [i]
     * @param k: 
     * @return: The ans array
     */
    public int[] business(int[] A, int k) {
        // Write your code here
        
        Deque<Integer> dq = new LinkedList<>();
        
        for (int i = 0; i < A.length && i < k + 1; i++) {
            while (!dq.isEmpty() && A[dq.peekLast()] > A[i]) {
                dq.pollLast();
            }
            
            dq.offer(i);
        }
        
        int[] res = new int[A.length];
        
        for (int i = 0; i < A.length; i++) {
            res[i] = A[i] - A[dq.peekFirst()];
            
            if (i > k && dq.peekFirst() == i - k) {
                dq.pollFirst();
            }
            
            if (i + k + 1 < A.length) {
                while (!dq.isEmpty() && A[dq.peekLast()] > A[i + k + 1]) {
                    dq.pollLast();
                }
                dq.offer(i + k + 1);
            }
        }
        
        return res;
    }
}

Learning emotion:

I also felt that I was useless because I was so late in updating and continuing my study. I came into contact with virtual currency around September last year, heard the news that my classmate made a fortune, wanted to realize the freedom of wealth with him, and took out my savings from small to large. At the beginning, it was only a small play, from 1000 to 3500. After taking out 1000 principal, I burst my warehouse and played all night, He began to study blockchain, learning k-line, macd and kdj, and then bought one in ETH2925 and put his savings in it. He also made money on Yuan universe coins. When the principal changed from 80000 to 150000, he became excited and invested all his money, but he still didn't fear the market, When I thought I could double the principal of 200000 yuan again, I fell all the way from December. Now, I understand that retail investors and novices can hardly get oil and water in this big capital dish that eats people and doesn't spit bones. They will be a senior at the beginning of school, learn to face the reality, keep updating every day in the future, learn to enrich themselves and be down-to-earth, Don't daydream about making a fortune, study steadily every day.

Learning output:

Learning blog * 1

Brush questions * 8

Topics: Java