当前位置:网站首页>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
How to save Two Numbers The result of subtraction .
3、 ... and 、 The difference between arrays and collections
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
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 .
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]);
}
}
边栏推荐
- Jenkins continuous integration operation
- Leetcode-78- subset (medium)
- About_ int128
- ES6解构赋值
- Addition and modification of JPA
- 408 true question - division sequence
- How the ET framework uses it to develop games
- Quantitative investment traditional index investment decision vs Monte Carlo simulation method
- Pipeline pipeline project construction
- Traditional machine learning classification model predicts the rise and fall of stock prices
猜你喜欢
Common skills for quantitative investment - drawing 3: drawing the golden section line
[JS component] calendar
Illustrator tutorial, how to add dashes and arrows in illustrator?
Most elements leetcode
Mathematical knowledge arrangement: extremum & maximum, stagnation point, Lagrange multiplier
[JS component] browse progress bar
Five classic articles worth reading
Alexnet implements image classification of caltech101 dataset (pytorch Implementation)
[JS component] create a custom horizontal and vertical scroll bar following the steam style
MySQL异常:com.mysql.jdbc.PacketTooBigException: Packet for query is too large(4223215 > 4194304)
随机推荐
707. design linked list
Pysmb usage
ES6 deconstruction assignment
Breadth first search for node editor runtime traversal
Vector|hdu-4841 round table questions
spiral matrix visit Search a 2D Matrix
Polymorphism and virtual function
sort
How to solve the problem of database?
Most elements leetcode
The tle4253gs is a monolithic integrated low dropout tracking regulator in a small pg-dso-8 package.
[JS component] simulation framework
MySQL performance analysis - explain
Rasa对话机器人之HelpDesk (三)
Minimum spanning tree problem
Leetcode-16- sum of the nearest three numbers (medium)
Sequence table - find main element
Leetcode-17- letter combination of phone number (medium)
Introduction to convolutional neural network
Work and life