当前位置:网站首页>Set and array conversion, list, array

Set and array conversion, list, array

2022-06-13 01:16:00 Roam-G

2016. The maximum difference between incremental elements

The difficulty is simple 67

I'll give you a subscript from  0  The starting array of integers  nums , The size of the array is  n , Please calculate  nums[j] - nums[i]  Obtainable   Maximum difference  , among  0 <= i < j < n  And  nums[i] < nums[j] .

return   Maximum difference  . If there is no... That meets the requirements  i  and  j , return  -1 .

Example 1:

 Input :nums = [7,1,5,4]
 Output :4
 explain :
 The maximum difference appears in  i = 1  And  j = 2  when ,nums[j] - nums[i] = 5 - 1 = 4 .
 Be careful , Even though  i = 1  And  j = 0  when  ,nums[j] - nums[i] = 7 - 1 = 6 > 4 , but  i > j  Does not meet the requirements of the problem surface , therefore  6  Not a valid answer .

Example 2:

 Input :nums = [9,4,3,2]
 Output :-1
 explain :
 There is no simultaneous satisfaction  i < j  and  nums[i] < nums[j]  Of these two conditions  i, j  Combine .

Example 3:

 Input :nums = [1,5,2,10]
 Output :9
 explain :
 The maximum difference appears in  i = 0  And  j = 3  when ,nums[j] - nums[i] = 10 - 1 = 9 .

Their thinking

  The code is at the end

Catalog

Their thinking ​

How to save   Two Numbers The result of subtraction .

***********

***********

Thinking first array Turn into list, use list Of add() Method add element , And then list Turn into array.

One 、 Array

Two 、 aggregate

3、 ... and 、 The difference between arrays and collections

Code


1. Problems encountered .

How to save   Two Numbers The result of subtraction .

         In general, you can't add elements to an array , Because they set the length at initialization , You can't change the length .

But there is an array that can be resized as ArrayList, That is, you can define a ArrayList aggregate , And then use add(element) Method to add elements to it , Still can add(index,element) Add an element to the specified subscript ; Examples are as follows :

List<Integer> list=new ArrayList<Integer>();

list.add(1);

list.add(2);

list.add(3);

list.add(2,4);

System.out.println(list);

***********

List It's an interface , and ArrayList Is a class . ArrayList Inherit and implement List.

List list = new ArrayList();

This sentence creates a ArrayList The object of the object is traced back to List. Now it's a List Object , There are some ArrayList Yes, but List No attributes and methods , It can't be used anymore . and ArrayList list=new ArrayList(); Create an object and keep it ArrayList All attributes of .

List The implementation of variable size array of interface , be located API Document java.util.ArrayList<E>. Implemented all optional list operations , And allow to include null All the elements inside . In addition to the implementation List Outside the interface , This class also provides some methods to manipulate the size of the array used to store the list internally .

Every ArrayList Each instance has a capacity . This capacity refers to the size of the array used to store list elements . It's always at least the size of the list .

***********

Thinking first array Turn into list, use list Of add() Method add element , And then list Turn into array.

But there will be a trap blind spot , In the array Turn into list In the process of , The use of asList() Method returns a final Of , Fixed length ArrayList class , Not at all java.util.ArrayList, Use it directly to add() or remove() It's invalid .

List<Integer> list=new ArrayList<Integer>();

list=Arrays.asList(sz);

list.add(5);

So how do you do that , In defining list When I was in the office, I was right array To convert , The code is as follows :

  • Array turn List: Use Arrays.asList(array) convert .

  • List turn Array : Use List Self contained toArray() Method .       

                                                                       a. Array -> aggregate

  • Integer []sz={3,2};

  • List<Integer> list=new ArrayList(Arrays.asList(sz));// Transform when you have to define

    list.add(1,5);

    Integer[] nsz=new Integer[list.size()];

    list.toArray(nsz);

    System.out.println(Arrays.toString(nsz));

  •  b. aggregate -> Array *****************************************************************************************************************

    Both of these methods put the list List The elements in are exported as Array , The difference is ,toArray() Method to export Object Type array , and toArray[T[] a] Method exports an array of the specified type .

    List Interface toArray() The method is to call Arrays.copyOf(elementData, size), take list The reference of the element object in is loaded in a new generated array .

  • List Interface toArray(T[] a) Method returns the specified type ( It has to be for list The parent of an element type or itself ) Array object of , If a.length Less than list The number of elements is called directly Arrays Of copyOf() Method to copy and return a new array object , The new array is also loaded list References to element objects , Otherwise, call System.arraycopy() take list References to element objects are placed in a Array , If a There's still space left in the array , It's in a[size] Place a null,size Namely list The number of elements in , This null The value can make toArray(T[] a) Method callers can judge null There's no more list Element .

object The data type is dataframe Special data types in , When a number appears in a column 、 character string 、 When there are two or more special characters and time formats , Will appear object type , Even if you separate different types , Still object type .

as follows replace() Function changes the data type , use astype() Function can only be converted once more object Format conversion , But sometimes not .

Arrays.toString

If you want to print out the contents of the array , Use it directly toString Method will only print out the address of the array , So you need to use Arrays Of toString Method , It can be seen from its internal implementation , This method supports that the input parameters can be long,float,double,int,boolean,byte,object Array of type

Arrays are not object-oriented , There are obvious defects , Collections completely make up for some of the shortcomings of arrays , More flexible and practical than array , It can greatly improve the efficiency of software development, and different collection framework classes can be applied to different occasions .

As follows :

1) Arrays are more efficient than collection classes .

2) Arrays can hold basic data types and objects , And the collection class can only put objects .

3) The array capacity is fixed and cannot be changed dynamically , Set class capacity changes dynamically .

4) Arrays can't tell how many elements are actually in them ,length Only told array The capacity of .

5) Collections can be implemented in a variety of ways and in different applications , Unlike arrays that only use sequential tables .



6) Sets exist in the form of classes , With encapsulation 、 Inherit 、 The characteristics of polymorphism and so on , Various complex operations can be realized through simple method and attribute calls , Greatly improve the efficiency of software development .

 

One 、 Array

An array is java Language built-in data types , It's a linear sequence , All other elements that can be accessed quickly , Arrays are different from other languages , When you create an array , His capacity is constant , And it can't be changed in the life cycle , also JAVA Arrays do boundary checks , If there is a cross-border phenomenon , Will be submitted to the RuntimeException Exception error , Of course, checking boundaries comes at the expense of efficiency .

Two 、 aggregate

JAVA Other collections are also provided ,list,map,set, They deal with objects as if they don't have their own type equally , But directly rooted in Object, In this way, you only need to create a collection , Put the object in , Just convert to your own type when you take it out .

 

3、 ... and 、 The difference between arrays and collections

One 、 The array declares what it holds Type of element , The set does not declare .

Two 、 Arrays are static , An array instance has a fixed size , Once created, you can't change the capacity . And collections can dynamically expand capacity , You can change the size dynamically as needed , Collections provide more member methods , Can meet more needs .

3、 ... and 、 The storage type of an array can only be one ( Basic types / Reference type ), The type of collection storage may not be a ( The type added without generics is Object).

Four 、 An array is java Data types built into the language , It's linear , Performing efficiency or type checking is the fastest .

Code

import java.util.ArrayList;
import java.util.List;

public class complex{

    public static void main(String[] args) {

        int[] nums ={7,1,5,4,3};
        int n = nums.length;
        List<Integer> list = new ArrayList<Integer>();// to use put sum = nums[j] - nums[i]
        for(int i = 0;i <= n-2;i++){
            for(int j = i + 1;j <= n-1;j++){
                list.add(nums[j] - nums[i]);
            }
        }
        System.out.println("List`s size = "+ list.size());
        System.out.println("list:");
        System.out.print(list);
        // to get the max numbers.   list -> array
        Integer[] ans = list.toArray(new Integer[0]);
        System.out.println();
        System.out.println("array`s length ="+ans.length);
        System.out.println("Array:");
        for (int i = 0 ;i < ans.length ;i ++  ){
            System.out.print(ans[i]+",");
        }
        //The Max . support the ans[0] is Max
            for (int j = 1;j < ans.length;j++){
                if(ans[0] < ans[j]){
                    int temp = ans[0];
                    ans[0] = ans[j];
                    ans[j] = temp;
                }
            }
        System.out.println();
        System.out.println("The Max Number is:");
        System.out.println(ans[0]);
    }
}

 

原网站

版权声明
本文为[Roam-G]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280555125656.html