从数组中获取存在的数字,放到新数组,新数组中数字不重复
时间: 2023-11-16 22:06:14 浏览: 32
可以使用一个 HashSet 来存储已经存在的数字,遍历原数组,判断当前数字是否存在于 HashSet 中,如果存在则跳过,否则将该数字添加到新数组和 HashSet 中。以下是 Java 代码示例:
```java
int[] nums = {1, 2, 2, 3, 4, 4, 5};
Set<Integer> set = new HashSet<>();
List<Integer> result = new ArrayList<>();
for (int num : nums) {
if (!set.contains(num)) {
result.add(num);
set.add(num);
}
}
```
在上述代码中,`result` 就是存储结果的新数组。
相关问题
从数组中获取存在的数字,放到新数组,新数组中数字不重复,给出c++示例
以下是一个简单的 C++ 示例,用于从一个数组中获取重复的数字,并将它们放入一个新数组中:
```cpp
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int newArr[n];
int count = 0;
for(int i = 0; i < n; i++)
{
bool isDuplicate = false;
for(int j = 0; j < count; j++)
{
if(arr[i] == newArr[j])
{
isDuplicate = true;
break;
}
}
if(!isDuplicate)
{
newArr[count] = arr[i];
count++;
}
}
cout << "New array: ";
for(int i = 0; i < count; i++)
{
cout << newArr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
New array: 1 2 3 4 5 6 7
```
在上面的示例中,我们首先定义了一个整数数组`arr`,其中包含一些重复的数字。然后,我们计算数组的大小并创建一个新的整数数组`newArr`和一个计数器变量`count`,用于跟踪新数组中的元素数量。
接下来,我们使用两个嵌套的循环遍历原始数组。对于每个元素,我们检查它是否已经出现在新数组中。如果没有,我们将其添加到新数组中,并递增计数器变量。
最后,我们遍历新数组并打印所有元素。请注意,新数组的大小等于计数器变量的值,因为我们只添加了不重复的元素。
从数组中获取存在的数字,放到新数组,新数组中数字不重复,记录数字出现次数,给出c++示例
以下是示例代码:
```c++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> getDistinctNumbers(vector<int>& nums) {
vector<int> res;
unordered_map<int, int> countMap;
for (int num : nums) {
if (countMap.find(num) == countMap.end()) {
res.push_back(num);
countMap[num] = 1;
} else {
countMap[num]++;
}
}
return res;
}
int main() {
vector<int> nums = {1, 2, 3, 2, 4, 1, 5, 6, 5};
vector<int> distinctNums = getDistinctNumbers(nums);
for (int num : distinctNums) {
cout << num << " appears " << countMap[num] << " times" << endl;
}
return 0;
}
```
该示例代码中,我们使用了一个 `unordered_map` 来记录每个数字出现的次数,并使用 `vector` 来存储不重复的数字。`getDistinctNumbers` 函数返回一个 `vector`,其中存储了不重复的数字。在 `main` 函数中,我们遍历 `distinctNums`,并输出每个数字出现的次数。