使用数组模拟无序表的差运算。a-b的结果放入c中。
时间: 2023-05-30 14:06:09 浏览: 96
假设a、b、c都是数组,且元素类型相同。
1. 遍历数组a,将a中不在b中的元素添加到c中。
2. 返回c数组。
示例代码如下:
```
int[] difference(int[] a, int[] b) {
int[] c = new int[a.length];
int index = 0; //c数组的下标
boolean flag; //标记a中的元素是否在b中出现过
for (int i = 0; i < a.length; i++) {
flag = false;
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
flag = true;
break;
}
}
if (!flag) {
c[index] = a[i];
index++;
}
}
int[] result = new int[index]; //创建一个长度为index的数组,存放c数组中有效的元素
System.arraycopy(c, 0, result, 0, index);
return result;
}
```
注意:如果a和b中有重复元素,c中也会存在重复元素。
相关问题
使用数组模拟无序表的差运算。a-b的结果放入c中。 void cha(int a[],int b[],int c[]) { } void main() { int a[10]={1,3,5,7,8}; int b[10]={2,4,6,8,9}; int c[10]={0}; cha(a,b,c); }
void cha(int a[], int b[], int c[]) {
int index = 0; // c数组的下标
int i = 0, j = 0; // a和b数组的下标
while (i < 5 && j < 5) { // 只要a和b数组还有元素
if (a[i] < b[j]) { // 如果a数组当前元素小于b数组当前元素
c[index++] = a[i++]; // 将a数组当前元素放入c数组
} else if (a[i] > b[j]) { // 如果a数组当前元素大于b数组当前元素
j++; // b数组下标加1,跳过b数组当前元素
} else { // 如果a数组当前元素等于b数组当前元素
i++; // a数组下标加1,跳过a数组当前元素
j++; // b数组下标加1,跳过b数组当前元素
}
}
while (i < 5) { // 如果a数组还有元素
c[index++] = a[i++]; // 将a数组剩余元素放入c数组
}
}
void main() {
int a[10] = {1, 3, 5, 7, 8};
int b[10] = {2, 4, 6, 8, 9};
int c[10] = {0};
cha(a, b, c);
}
将数组里面的值全部放入set集合中
好的,您可以使用下面的代码将数组中的值全部放入set集合中:
```python
array = [1, 2, 3, 3, 4, 5, 5, 6]
set_array = set(array)
print(set_array)
```
输出结果为:
```
{1, 2, 3, 4, 5, 6}
```
这段代码将数组 `[1, 2, 3, 3, 4, 5, 5, 6]` 中的值放入了一个set集合中,并输出了set集合中的元素。由于set集合是无序且不允许重复元素的,所以输出结果中只有一个3和一个5。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)