Java线性搜索具有多个关键匹配的数组

时间:2017-06-27 06:18:24

标签: java arrays jgrasp

尝试实施执行以下操作的程序:

- 可以通过用户输入重新运行的程序(循环时)

- 允许用户输入所需的数组大小,创建该大小的数组, 使用for循环将元素输入到数组中,并输入所需的键 从中做一个线性搜索方法

我想修改线性搜索方法,以数组的形式返回 arrayName [i] ==键值的所有实例的索引值;这是我陷入困境的部分。

例如,如果用户输入4作为数组大小; 1,2,3,3为元素; 2作为线性搜索的所需键,然后它将打印数组{1,2}作为键与元素值匹配的索引。

到目前为止,这是我的代码:

create or replace view combo_table1 as 
Select UNIQUE Leavetype, 0 AS Leave_Availed, LEAVEBALANCE 
from LEAVE_ELIGIBILITY INNER JOIN EMPLOYEE ON LEAVE_ELIGIBILITY.DEPARTMENT= EMPLOYEE.DEPARTMENT AND LEAVE_ELIGIBILITY.DESIGNATION= EMPLOYEE.DESIGNATION 
WHERE EID='78';

create or replace view combo_table2 as 
SELECT LEAVE_TYPE as Leavetype, SUM(TIME_PERIOD) AS Leave_Availed, 0 as LEAVEBALANCE 
FROM EMPLOYEE_LEAVE 
WHERE EMPLOYEEID='78'
GROUP BY LEAVE_TYPE, LEAVEBALANCE;

SELECT Leavetype, sum(LEAVEBALANCE), sum(leave_availed)
FROM (
  select *
    from combo_table1
    UNION ALL
    select * from combo_table2
)
group by Leavetype;

1 个答案:

答案 0 :(得分:0)

问题是分配一个正确大小的数组(匹配数)。此解决方案使用大型数组并在最后调整大小:

  public static int [] linearSearch(double[] list, double key) {
    int[] indices = int[list.length];
    int n = 0;
    for (int i = 0; i < list.length; i++) {
      if (key == list[i]){
        îndices[n++] = i;
      }
    }
    int[] result = new int[n];
    for (int i = 0; i < n; ++i) {
        result[i] = indices[i];
    }
    return result;
  }