Java implements missing integer search function


package test;
/**
 * Question: There is a set of numbers, from 1 to n, in which the number of x is reduced, the order is also disrupted, and it is placed in an array of nx, please find the missing numbers.  
         Idea: Declare a new array toolsArray of length n+1,
          then traverse the array src that is shuffled and missing numbers,
          such as the data z traversed in src, let toolsArray[z]=1; and then traverse the toolsArray, Find the subscript whose value is not 1;  
 * @author Kui
 *
 */
public class HelloA {
public static void main(String[] args) {
//Define an array of int type with missing integers and initialize it  
int[] src={ 1,2,3,4,6,9};
//Call the search method
System.out.println("The missing integer is: " + getRemoveNums(src,9));
} /** * @param src -- Array of missing integers * @param maxLength -- maximum length of array * @return result -- missing integer string */






private static String getRemoveNums(int[] src, int maxLength){
//Define a string to receive the searched characters and initialize
String result = "";
//Define a new maxLength + 1 array 
//for Store the formatted src array
//1 means that the existing element 0 is not a missing element
int[] toolArray = new int[maxLength + 1];
//initialize the first element of the array to 1 
toolArray[0]=1;
/ / Traverse the missing array
for (int i = 0; i < src.length; i++) {
//Receive array elements
int num = src[i];
//If the array element exists, the format is 1. If it is missing, the default value is 0 
toolArray [num] = 1;
}
//traverse tool format array
for (int i = 0; i < toolArray.length; i++) {
//receive elements of formatted array
int num = toolArray[i];
//output format Array
System.out.println("toolArray : " + toolArray[i]);
//If the array element is not 1, it means the missing array 
if (num != 1 ) {
//Remove the missing array: that is, the subscript value of the formatted array element is not 1
result += i + " ";
}
}
/ /return string result with missing integer
return result; } }







Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324749409&siteId=291194637