前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linear Search

Linear Search

作者头像
废江_小江
发布2022-09-05 13:59:37
2520
发布2022-09-05 13:59:37
举报
文章被收录于专栏:总栏目

Question

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

n ≤ 10000

q ≤ 500

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5

1 2 3 4 5

3

3 4 1

Sample Output 1

3

Sample Input 2

3

3 1 2

1

5

Sample Output 2

0

Sample Input 3

5

1 1 2 2 3

2

1 2

Sample Output 3

2

Notes

Meaning

题目很简单,但是这里主要讲一个:线性搜索在引入标记之后,效率能提升常数倍。

Coding

代码语言:javascript
复制
#include<iostream>
#include<cstdio>
#include<stdio.h>
using namespace std;
//带有标记的线性搜索
int search(int A[],int n, int key) {
	int i = 0;
	A[n] = key;//标记搜索先给关键字放在末尾
	while (A[i] != key)
		i++;
	return i != n;
}
int A[100005];
int main() {
	int n, q, key,sum=0;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
		scanf("%d", &A[i]);
	scanf("%d", &q);
	for (int i = 0; i < q; i++) {
		scanf("%d", &key);
		if (search(A, n, key))
			sum++;
	}
	printf("%d\n", sum);
}

Summary

向线性搜索种引入“标记”能够以将算法效率提升常数倍。

原始:

代码语言:javascript
复制
LinearSearch()
for i 从 0 到n-1
if A[i] 与key相等
return i
returnNOT_FOUND

改进后,给要查找的数放在数组末尾,用作标记。

代码语言:javascript
复制
int search(int A[],int n, int key) {
	int i = 0;
	A[n] = key;//标记搜索先给关键字放在末尾
	while (A[i] != key)
		i++;
	return i != n;
}

废江博客 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权

转载请注明原文链接:Linear Search

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-04-09),如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Question
  • Meaning
  • Coding
  • Summary
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档