int 배열에서 요소의 인덱스를 찾는 방법은 무엇입니까?
유형의 Java 배열에서 특정 값의 색인을 어떻게 찾을 수 int있습니까?
Arrays.binarySearch정렬되지 않은 배열을 사용해 보았지만 때로는 정답 만 제공합니다.
Integer[] array = {1,2,3,4,5,6};
Arrays.asList(array).indexOf(4);
이 솔루션은 List 유형의 새 개체를 만들기 때문에 스레드로부터 안전합니다.
또한 매번 새로운 객체를 생성 할 것이기 때문에 루프 또는 이와 유사한 방식으로 이것을 호출하고 싶지 않습니다.
Guava 컬렉션을 사용하는 경우 또 다른 옵션은 Ints.indexOf입니다.
// Perfect storm:
final int needle = 42;
final int[] haystack = [1, 2, 3, 42];
// Spoiler alert: index == 3
final int index = Ints.indexOf(haystack, needle);
공간, 시간 및 코드 재사용이 중요한 경우에 좋은 선택입니다. 또한 매우 간결합니다.
API를 살펴보면 먼저 배열을 정렬해야한다고 말합니다.
그래서:
Arrays.sort(array);
Arrays.binarySearch(array, value);
배열을 정렬하지 않으려면 :
public int find(double[] array, double value) {
for(int i=0; i<array.length; i++)
if(array[i] == value)
return i;
}
이 메서드를 클래스에 복사
public int getArrayIndex(int[] arr,int value) {
int k=0;
for(int i=0;i<arr.length;i++){
if(arr[i]==value){
k=i;
break;
}
}
return k;
}
두 개의 perameters Array 및 value를 전달하여이 메서드를 호출하고 반환 값을 정수 변수에 저장합니다.
int indexNum = getArrayIndex(array,value);
감사합니다
목록으로 변환 한 다음 indexOf 메서드를 사용할 수 있습니다.
Array.asList(array).indexOf(1);
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#asList(T ...) http://download.oracle.com/javase/1.5.0 /docs/api/java/util/List.html#indexOf(java.lang.Object )
이진 검색을 사용하기 전에 값을 정렬해야합니다. 그렇지 않으면 수동 방법은 탭의 모든 int를 시도하는 것입니다.
public int getIndexOf( int toSearch, int[] tab )
{
for( int i=0; i< tab.length ; i ++ )
if( tab[ i ] == toSearch)
return i;
return -1;
}//met
대체 방법은 맵의 각 값에 대한 모든 인덱스를 매핑하는 것입니다.
tab[ index ] = value;
if( map.get( value) == null || map.get( value) > index )
map.put( value, index );
그런 다음 map.get (value)를 사용하여 색인을 가져옵니다.
감사합니다, Stéphane
@pst, 귀하의 의견에 감사드립니다. 다른 대체 방법을 게시 할 수 있습니까?
최신 Java를 사용하여이 문제를 해결할 수 있습니다. 아래 코드를 사용하십시오.
static int findIndexOf(int V, int[] arr) {
return IntStream.range(1, arr.length).filter(i->arr[i]==V).findFirst().getAsInt();
}
Integer[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
List<Integer> arrlst = Arrays.asList(arr);
System.out.println(arrlst.lastIndexOf(1));
단순한:
public int getArrayIndex(int[] arr,int value) {
for(int i=0;i<arr.length;i++)
if(arr[i]==value) return i;
return -1;
}
찾고있는 인덱스를 찾을 때까지 배열을 살펴 보거나 List대신 사용할 수 있습니다 . 를 사용하여 배열을 목록으로 변환 할 수 있습니다 asList().
/**
* Method to get the index of the given item from the list
* @param stringArray
* @param name
* @return index of the item if item exists else return -1
*/
public static int getIndexOfItemInArray(String[] stringArray, String name) {
if (stringArray != null && stringArray.length > 0) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
int index = list.indexOf(name);
list.clear();
return index;
}
return -1;
}
다음과 같이 할 수 있습니다.
public class Test {
public static int Tab[] = {33,44,55,66,7,88,44,11,23,45,32,12,95};
public static int search = 23;
public static void main(String[] args) {
long stop = 0;
long time = 0;
long start = 0;
start = System.nanoTime();
int index = getIndexOf(search,Tab);
stop = System.nanoTime();
time = stop - start;
System.out.println("equal to took in nano seconds ="+time);
System.out.println("Index of searched value is: "+index);
System.out.println("De value of Tab with searched index is: "+Tab[index]);
System.out.println("==========================================================");
start = System.nanoTime();
int Bindex = bitSearch(search,Tab);
stop = System.nanoTime();
time = stop - start;
System.out.println("Binary search took nano seconds ="+time);
System.out.println("Index of searched value is: "+Bindex);
System.out.println("De value of Tab with searched index is: "+Tab[Bindex]);
}
public static int getIndexOf( int toSearch, int[] tab ){
int i = 0;
while(!(tab[i] == toSearch) )
{ i++; }
return i; // or return tab[i];
}
public static int bitSearch(int toSearch, int[] tab){
int i = 0;
for(;(toSearch^tab[i])!=0;i++){
}
return i;
}
}
XOR 추가 :)
for 루프를 사용하는 주요 방법에서 :-내 예제의 세 번째 for 루프가이 질문에 대한 답입니다. -제 예에서는 20 개의 임의의 정수 배열을 만들고 변수에 가장 작은 숫자를 할당하고 루프 수를 세는 동안 배열의 위치가 가장 작은 값에 도달하면 루프를 중지했습니다.
import java.util.Random;
public class scratch {
public static void main(String[] args){
Random rnd = new Random();
int randomIntegers[] = new int[20];
double smallest = randomIntegers[0];
int location = 0;
for(int i = 0; i < randomIntegers.length; i++){ // fills array with random integers
randomIntegers[i] = rnd.nextInt(99) + 1;
System.out.println(" --" + i + "-- " + randomIntegers[i]);
}
for (int i = 0; i < randomIntegers.length; i++){ // get the location of smallest number in the array
if(randomIntegers[i] < smallest){
smallest = randomIntegers[i];
}
}
for (int i = 0; i < randomIntegers.length; i++){
if(randomIntegers[i] == smallest){ //break the loop when array location value == <smallest>
break;
}
location ++;
}
System.out.println("location: " + location + "\nsmallest: " + smallest);
}
}
코드는 모든 숫자와 해당 위치, 가장 작은 숫자 다음에 가장 작은 숫자의 위치를 출력합니다.
누군가가 여전히 답을 찾고 있다면-
[Apache Commons Library] [1]에서 ArrayUtils.indexOf ()를 사용할 수 있습니다.
Java 8을 사용하는 경우 Strean API를 사용할 수도 있습니다.
public static int indexOf(int[] array, int valueToFind) { if (array == null) { return -1; } return IntStream.range(0, array.length) .filter(i -> valueToFind == array[i]) .findFirst() .orElse(-1); }
static int[] getIndex(int[] data, int number) {
int[] positions = new int[data.length];
if (data.length > 0) {
int counter = 0;
for(int i =0; i < data.length; i++) {
if(data[i] == number){
positions[counter] = i;
counter++;
}
}
}
return positions;
}
Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted. Java provides us with an inbuilt function which can be found in the Arrays library of Java which will rreturn the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search.
public static int findIndex(int arr[], int t) {
int index = Arrays.binarySearch(arr, t);
return (index < 0) ? -1 : index;
}
Integer[] array = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < array.length; i++) {
if (array[i] == 4) {
system.out.println(i);
break;
}
}
참고URL : https://stackoverflow.com/questions/6171663/how-to-find-the-index-of-an-element-in-an-int-array
'IT TIP' 카테고리의 다른 글
| Ajax에서 GET 대 POST (0) | 2020.10.25 |
|---|---|
| UILabel의 배경색에 애니메이션을 적용하는 방법은 무엇입니까? (0) | 2020.10.25 |
| cat의 출력을 cURL로 파이프하여 파일 목록을 다운로드합니다. (0) | 2020.10.25 |
| .NET 경로가 디렉토리가 아닌 파일인지 확인하는 방법은 무엇입니까? (0) | 2020.10.25 |
| 위도와 경도에 대한 올바른 데이터 유형? (0) | 2020.10.25 |