簡體   English   中英

如何編寫一個程序,返回 Java 中 integer 數組中給定值最后一次出現的索引 position?

[英]How to write a program that returns the index position of last occurrence of a given value in an integer array in Java?

例如給定一個 integer 數組:

{1, 2, 3, 1, 4} 和 integer 值 1

該方法將返回 3 作為給定值的最后一個索引 position。 如果數組不包含給定值,則該方法應返回 -1。

我的代碼:

public int lastIndexOf(int[] values, int value) {

    for( int i=0; i< values.length ; i ++ )
        if( values[ i ] == value)
            return i;

    return -1;
}

結果我得到了什么:

 org.opentest4j.AssertionFailedError: Expected:5 Actual:-1

預期結果:

 @Test
public void testLastIndexOf() {
    assertEquals(5, main.lastIndexOf(new int[]{1, 2, 3, 4, 5, 1}, 1));
    assertEquals(-1, main.lastIndexOf(new int[]{2, 3, 3, 2, 4, 5, 4}, 1));
    assertEquals(0, main.lastIndexOf(new int[1], 0));
    assertEquals(4, main.lastIndexOf(new int[]{0, -1, 1, 8, 8, -1, 6, -2}, 8));
}

因為你想要最后一個索引,所以你可能會以相反的順序讀取數組,從頭到尾能夠在第一次匹配時停止

public int lastIndexOf(int[] values, int value) {
    for (int i = values.length - 1; i >= 0; i--) {
        if (values[i] == value) {
            return i;
        }
    }
    return -1;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM