微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在数组中查找目标整数值

如何解决在数组中查找目标整数值

这是我到目前为止所拥有的:

public class ArraySort {

    //method to search the array for an int x

    public int search(int x) {
        int[] testArray = {};
        for (int i = 0; i < testArray.length; ++i) {
            if (testArray[i] == x) {
                return (x);
            } else if (testArray[i] != x) {
                return -1;
            } else {
                return 1;
            }
        }
    }
    //main method

    public static void main(String[] args) {
        int[] testArray = {1,2,3};
        int x = 3;

        System.out.print(search(x));

    }
}

解决方法

您不需要两个else语句:

public int search(int x) {
    int[] testArray = {1,2,3,4,5,6};   // put some numbers here
    for (int i = 0; i < testArray.length; i++) {
        if (testArray[i] == x) {
            return (x);
        }
    }
    return -1;
}

考虑一下:在原始循环的第一次迭代中,是否有任何情况下您不会遇到return语句? (提示:答案是否定的)。因此,只需查看第一个数字,循环便会返回。

还,您的搜索数组为空吗?

编辑:我刚刚注意到您正在尝试通过主方法传递数组

因此,如果要将数组传递给搜索方法,则需要为其创建一个参数:

public int search(int x,int[] testArray) {
    for (int i = 0; i < testArray.length; i++) {
        if (testArray[i] == x) {
            return (x);
        }
    }
    return -1;
}

public static void main(String[] args) {
    int[] testArray = {1,3};
    int x = 3;
    System.out.print(search(x),testArray);  // pass the array here

}
,

取决于数组是已排序还是未排序。

让我们假设数组未排序。我们可以在O(n)时间内线性搜索元素的索引。第一个建议是将数组传递给方法search()。

public int search(int[] testArray,int x) {
    int arrLength = testArray.length;
    int i = 0;
    
    // Traverse in the array
    while (i < arrLength) {
        if (testArray[i] == x) {
            return i;        
        } else {
            i = i + 1;
        }
    }
    return -1;
}

要在main方法中执行:

System.out.println(search(testArray,1));
,

首先,您需要在方法中将testArray作为参数传递。 如果在数组中找不到值,则可以引发异常。 请参见以下示例:

public static int search(int x,int[] testArray) {
    for (int i = 0; i < testArray.length; ++i) {
        if (testArray[i] == x) {
            return (x);
        }
    }
    throw new RuntimeException("Element not present in array exception");
}
//main method

public static void main(String[] args) {
    int[] testArray = {1,3};
    int x = 3;

    System.out.print(search(x,testArray));

}

此外,您可以使用Java 8

    public static void main(String[] args) {
        int[] testArray = {1,3};
        int x = 3;
        System.out.println(Arrays.stream(testArray).filter(value -> value ==x).findFirst().orElseThrow(() -> new RuntimeException("Element not present in array exception")));
    }
,

您应该将数组传递给函数。现在,根据您是要返回数字本身还是返回数字在数组中的位置,两个函数将略有不同,如下所示:

import argparse

import tensorflow as tf
from tensorflow.python.framework import tensor_util


def print_pb_weights(pb_filepath):
    graph_def = tf.GraphDef()
    with tf.gfile.GFile(pb_filepath,"rb") as f:
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def,name='')

    for node in graph_def.node:
        if node.op == 'Const':
            print('-' * 60)
            print('op:',node.op)
            print('name:',node.name)
            arr = tensor_util.MakeNdarray(node.attr['value'].tensor)
            print('shape:',list(arr.shape))
            print(arr)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('pb_filepath')
    args = parser.parse_args()

    print_pb_weights(args.pb_filepath)

输出:

public class Main {
    public static void main(String[] args) {
        int[] testArray = { 1,3 };
        int x = 3;

        System.out.println(search(testArray,x));
        System.out.println(searchIndex(testArray,x));

        x = 5;
        System.out.println(search(testArray,x));
    }

    /*
     * Returns the search element if found; otherwise returns -1
     */
    public static int search(int[] arr,int x) {
        for (int i = 0; i < arr.length; ++i) {
            if (arr[i] == x) {
                return x;// Return the element itself
            }
        }
        return -1;
    }

    /*
     * Returns the index of search element if found; otherwise returns -1
     */
    public static int searchIndex(int[] arr,int x) {
        for (int i = 0; i < arr.length; ++i) {
            if (arr[i] == x) {
                return i;// Return the index of the element
            }
        }
        return -1;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?