Java sample for the number of iterations of an array element and the size of a Java string comparison
- 2020-04-01 03:19:34
- OfStack
public static Map<String, Integer> arraySearch(int[] array,int max){
//The result set
Map<String, Integer> resultMap = new HashMap<String, Integer>();
//Number of repetitions
int maxCount = 0;
//Number of repetitions to many
int value = 0;
try{
//Initializes an array of data that holds the number of occurrences of each element
int[] dataArray = new int[max+1];
//Traversing the array to be looked for, with each element as subscript, directly locate the data array, and perform the +1 operation to indicate that it appears once
for(int i : array){
dataArray[i]++;
}
//Find the maximum value in the data array
for(int i=0;i<dataArray.length;i++){
if(dataArray[i]>maxCount){
maxCount=dataArray[i];
value=i;
}
}
}catch (Exception e) {}
resultMap.put("maxCount", maxCount);
resultMap.put("value", value);
return resultMap;
}
public static int compareString(String first,String second){
int result = 0;
try{
//Turn null empty
first = first==null?"":first;
second = second==null?"":second;
//Record the length of the string in advance to avoid repeated reads
int firstLength=first.length();
int secondLength=second.length();
//Handles special cases with empty strings
if("".equals(first) || "".equals(second)){
//Whoever long small
result = secondLength-firstLength;
}else{
//Temporary space for storing the sum of ASCII codes
int firstCount = 0;
int secondCount = 0;
//The smaller of the two Numbers by pure arithmetic is really bt
int minLength = (secondLength*(firstLength/secondLength) + firstLength*(secondLength/firstLength))/(firstLength/secondLength + secondLength/firstLength);
//Truncate bit by bit the shorter number of bits in two strings to prevent overbounds
for(int i=0;i<minLength;i++){
//ASCII and
firstCount+=first.substring(i,i+1).getBytes()[0];
secondCount+=second.substring(i,i+1).getBytes()[0];
//The sum is not equal to the sum, which means that the magnitude has been compared
if(firstCount!=secondCount){
break;
}
}
if(firstCount==secondCount){
//Long length
result = firstLength-secondLength;
}else{
//The sum is big and the sum is big
result = firstCount-secondCount;
}
}
}catch (Exception e) {}
return result;
}