在数组中查找匹配项 [英] find matching items in an array

查看:259
本文介绍了在数组中查找匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

如何在整数数组中搜索所有匹配的值然后返回它们的索引



谢谢提前,

z3ngew

Hello everyone,
How can i search for all matching values in an array of integers and then return their indexes

Thanks in advance,
z3ngew

推荐答案

我们不做你的功课 - 你得到了功劳,所以你做的工作是公平的好! :笑:



但这并不困难:

设置一个简单的循环来检查每个数组条目是否匹配。

唯一的复杂因素是你想要返回一个可变数量的索引值 - 这意味着在实践中你需要malloc一个足以满足所有索引的数组,并且具有终止值(负指数说)或参数值返回索引计数。





如果有2对匹配,我应该返回2d数组



啊!我明白你的意思了......

你有一个输入数组:

We don't do your homework - you get the credit, so it's only fair you do the work as well! :laugh:

But this isn't difficult:
Set up a simple loop to check each array entry to see if it matches.
The only complication is that you want to return a variable number of index values - which means in practice that you will need to malloc an array that is big enough for all indexes possible, and have a termination value (a negative index say) or a parameter value to return the indexes count.


"if there is 2 pair of matches, i should return 2d array or not"

Ah! I see what you mean now...
You have an input array:
7,3,2,6,3,5,2,1,9,6

并且您想要返回:

And you want to return:

2, 6
1, 4
3, 9

在这种情况下,这样做有点复杂。

首先,返回值对存在问题 - 是的,你可以使用2D数组,这会很好(记得分配输入/ 2的大小)作为元素对的数量 - 但如果你的输入中有三个匹配会发生什么?

我宁愿接受创建一个 struct ,它包含值,数组或索引值列表。然后我会返回一个指针数组......或者更好的链接列表。 (这取决于你的能力水平和你到目前为止学到的东西你想要去的方式)



要实际进行匹配,我会作弊。我为元素设置了一个索引数组,然后对它进行排序,以便引用相同数字的索引并排:

In which case it's a little more complex to do.
First off there is a problem with returning the value pairs - yes, you could use a 2D array, and that would work well (remember to allocate size of input / 2) as the number of pairs of elements - but what happens if there are three matches in your input?
I would instead be tempted to create a struct which held the value, and an array, or list of index values. I would then return an array of pointers to those...or better a linked list of them. (It depends on your ability level and what you have learned so far which way you will want to go)

To actually do the matching, I'd cheat. I'd set up an array of indexes to elements, and then sort it so that indexes which refer to the same number were side by side:

Input:   7,3,2,6,3,5,2,1,9,6
Indexes: 0,1,2,3,4,5,6,7,8,9




Input:   7,3,2,6,3,5,2,1,9,6
Indexes: 7,2,6,1,4,5,3,9,0,8

索引引用的值按升序排列,因此相等值的索引是并排的:1& 4和3& 9

现在你所要做的就是遍历索引数组,比较它们引用的值,并为那些相同的值创建输出值。



这有意义吗?如果没有用箭头在纸上试试,你应该明白我的意思。

The values the indexes refer to are in ascending order, so the indexes for equal values are side by side: 1 & 4, and 3 & 9
Now all you have to do is traverse the indexes array comparing the values they refer to and create output values for those that are the same.

Does that make sense? If not try it on paper with arrows and you should see what I mean.


这篇关于在数组中查找匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆