数组中丢失数字的示例丢失的数字是数组中连续数字序列中丢失的数字。
考虑一个数组;
arr=[1,2,3,4,5,6,8]
上面的数组‘arr’中,缺少了7,所以7就是丢失的数字
示例2
考虑一个数组;
arr=[1,2,3,4,5,6,7,8,9,11]
上面的数组'arr'中,缺少10,所以10就是丢失的数字
现在,我们将讨论 java 中查找流中丢失的数字的各种方法。
方法一:使用stream()和sum()方法在这种方法中,我们使用stream()函数并将数组转换为流,然后使用sum()函数计算流的总和并存储在'actualsum'变量中,然后我们计算预期总和使用公式 n*(n+1)/2 ,然后我们使用预期总和 - 实际总和找到丢失的数字。
算法使用一些值初始化数组。
使用stream()和sum()方法计算数组的总和
计算数组长度,并使用 n 项之和公式求出连续数字的预期总和。
减去期望值和总和,将其分配给变量并打印。
stream() - 'stream()'方法用于创建元素流,以便我们可以使用filter()、map()、reduce()等方法来处理数据 p>arrays.stream(collection)
sum() - 此方法用于计算集合中所有元素的总和。
stream.sum()
示例在这个例子中,我们将使用stream()和sum()方法通过java来查找丢失的数字。
import java.util.arrays;public class main { public static void main(string[] args) { int[] array = {1, 2, 3, 5}; int sum = arrays.stream(array).sum(); int n = array.length + 1; int expectedvalue = (n * (n + 1)) / 2; int lostnumber = expectedvalue - sum; system.out.println(lost number + lostnumber); }}
输出lost number 4
方法 2:使用异或在这种方法中,我们计算n个值的xor并存储在expectedvalue变量中,然后计算xor的actualvalue,最后我们在之间执行xor expectedvalue 和actualvalue 来获取丢失的数量。
算法使用一些值初始化数组。
计算数组的长度并加 1,因为我认为数组中的实际数字应该是 array.length+1 并分配给变量“n”。
将期望值设置为 1,并使用 xor 运算符使用 for 循环计算期望值,直到 n。
将期望值设置为数组[0],并使用 xor 运算符使用 for 循环计算数组中存在的元素的实际值。
使用预期值和实际值的 xor 运算符计算丢失的数字并打印
异或运算 (^) - 异或运算执行按位运算,如果两个位都为 1,则返回 1,否则返回 0。它由 ^ 表示。
a ^ b // where 'a' and 'b' are integers.
示例在此示例中,我们将使用 xor 运算符并使用 java 查找丢失的数字。
public class main { public static void main(string[] args) { int[] array = {1, 2, 3, 5}; // input array with missing number int n = array.length + 1; // total number of elements if no number was missing int expectedvalue = 1; // expected xor value if no number was missing for (int i = 2; i <= n; i++) { expectedvalue ^= i; // xor all elements from 1 to n to get expected value } int actualvalue = array[0]; // start with first element of array for (int i = 1; i < array.length; i++) { actualvalue ^= array[i]; // xor all elements of array to get actual value } int lostnumber = expectedvalue ^ actualvalue; // xor expected and actual values to get lost number system.out.println(the lost number is + lostnumber); }}
输出the lost number is 4
方法 3:使用 hashset在这个例子中,我们将使用数据结构hashset和hashset的内置方法来使用java查找丢失的数字。
算法使用一些值初始化数组。
创建哈希集并使用 for 循环迭代数组并将值添加到哈希集。
使用 for 循环,迭代 i 到 array.length+1 并使用 contains() 方法检查集合中缺失的值并打印丢失的数字。
hashset - 哈希集是不允许重复元素的无序对象集合。
hashset<datatype> objname = new hashset<datatype>();
contains() - 此方法检查集合中是否存在值并返回布尔值。
setobjname.contains(value)
示例在这种方法中,我们将数组的所有元素存储在 hashset 中,然后从 1 迭代到 array.length+1 值,并检查所有值是否都存在于集合中,如果不存在任何值,则这就是丢失了数值并打印它。
import java.util.arrays;import java.util.hashset;public class main { public static void main(string[] args) { int[] array = {1, 2, 3, 5}; hashset<integer> set = new hashset<integer>(); for (int i : array) { set.add(i); } for (int i = 1; i <= array.length + 1; i++) { if (!set.contains(i)) { system.out.println(lost number: + i); break; } } }}
输出lost number: 4
因此,在本文中,我们学习了使用 java 编程语言查找丢失号码的不同方法。
以上就是java程序查找丢失的数字的详细内容。