简体   繁体   English

计算非重复整数

[英]Counting non repeating integers

I need help with a coding question. 我需要一个编码问题的帮助。 I would like some tips on finding the answer but not the answer itself. 我想找到答案的一些提示,但不是答案本身。

Sample input looks like this 3112. 示例输入看起来像3112。

Sample output is 2 because the integers doesn't repeat. 样本输出为2,因为整数不重复。

here's the code 这是代码

public static int lonelyInteger(int[] arr)
{

    need to code this 

}


public static void main(String[] args) throws IOException
{
    Scanner in = new Scanner(System.in);
    final String fileName = System.getenv("OUTPUT_PATH");
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    int res;

    int _arr_size = Integer.parseInt(in.nextLine());
    int[] _arr = new int[_arr_size];
    int _arr_item;
    for(int _arr_i = 0; _arr_i < _arr_size; _arr_i++)
    {
        _arr_item = Integer.parseInt(in.nextLine());
        _arr[_arr_i] = _arr_item;
    }

    res = loneyInteger(_arr);
    bw.write(String.valueOf(res));
    bw.newLine();

    bw.close();
}

Write a loop that iterates from the start to the end of arr , and check the element in front and behind at each index for it it contains a different value. 编写一个从arr的开头到结尾迭代的循环,并检查每个索引前后的元素,它包含不同的值。 If the value is different from the previous and next elements, add one to the counter. 如果该值与上一个和下一个元素不同,请向计数器添加一个。 Make sure to do a check that the index in front or behind aren't equal to -1 or arr.length before accessing those indexes. 在访问这些索引之前,请务必检查前面或后面的索引是否不等于-1arr.length

Spoiler: 扰流板:

int count = 0; for (int i = 0; i < arr.length; i++) if (i-1 >= 0 && arr[i] == arr[i-1] || i+1 < arr.length && arr[i] == arr[i+1]) continue; else count++; return count;

You can make a counter for the integers that repeated themselves while you read them . 您可以在读取它们时重复自己的整数计数器。

For example : 例如 :

for(int _arr_i = 0; _arr_i < _arr_size; _arr_i++)
{
   _arr_item = Integer.parseInt(in.nextLine());
   if (itemNotInList(_arr_item))
      repeatedItemsCounter++;
}
unrepeadedItems = allItems - repeatedItemsCounter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM