【问题标题】:sequential search backward [closed]向后顺序搜索[关闭]
【发布时间】:2020-03-31 14:10:00
【问题描述】:

我正在学习顺序搜索并且有顺序搜索代码,但我想找到搜索过程从右(数据末尾)到左(数据开头)的数字。

public static void main(String[] args) {
        int []a={5,6,9,2,8,1,7};
        int key=8;
        boolean f=false;
        for (int i = 0; i < a.length; i++) {
            if(key == a[i]){
                System.out.println("data found on index "+i);
                f=true;
                break;
            }
        }
        if (f=false){
            System.out.println("data not found");
        }
    } 

【问题讨论】:

  • 你能更好地解释一下吗? 查找数字是什么意思?你的意思是有多少?还是您的意思是找到的索引?
  • 找到的索引

标签: java search sequential


【解决方案1】:

如果你想从后向前搜索,我认为你可以编辑 for 循环选项。
for (int i = a.length - 1 ; i &gt;= 0; i--)

【讨论】:

    【解决方案2】:

    如果您要查找与键匹配的所有索引,则可以创建一个方法,该方法返回一组整数值,表示找到的每个索引。您仍然可以使用从 array.length - 1 到 0 的简单 for 循环从右到左循环。

        static Set<Integer> matchingIndices(int[] array, int key) {
            Set<Integer> indices = new HashSet<>();
    
            for (int index = array.length - 1; index > -1; index--) {
                int valueAtIndex = array[index];
    
                if (valueAtIndex == key) {
                    indices.add(index);
                }
            }
            return indices;
        }
    

    例子

        public static void main(String[] args) {
            int [] a= {5,6,9,2,8,1,7};
    
            int key = 8;
    
            Set<Integer> indices = matchingIndices(a, key);
    
            if (indices.isEmpty()) {
                System.out.println("No index found for key.");
            } else {
                System.out.println("Key found at following indices: " + indices);
            }
        }
    

    如果您想使用相同的键从右到左查找第一个索引,只需返回一个 int 并快速失败。

        static int firstIndex(int[] array, int key) {
            for (int index = array.length - 1; index > -1; index--) {
                int valueAtIndex = array[index];
    
                if (valueAtIndex == key) {
                    return index;
                }
            }
            throw new IllegalStateException("No index found with the same key.");
        } 
    

    例子

        public static void main(String[] args) {
            int [] a= {5,6,9,2,8,1,7};
    
            int key = 8;
    
            try {
                int index = firstIndex(a, key);
    
                System.out.println(String.format("Found key at index %s", index));
            } catch (IllegalStateException ise) {
                System.out.println("No index found.");
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 2011-03-08
      • 1970-01-01
      • 2012-03-02
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多