如何检查一个数组是否包含一个值?

205 阅读1分钟

如何检查一个数组是否包含一个值?

有很多方法可以检查数组是否包含任何特定的值,其中之一就是。

例子

输入:arr[] = {10, 30, 15, 17, 39, 13}, key = 17
输出:真

输入: arr[] = {3, 2, 1, 7, 10, 13}, key = 20
输出:假的

办法

使用内建函数。在C语言中,没有内置的函数用于搜索

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
	vector<int> v{ 10, 25, 15, 12, 14 };
	int key = 15;

	// Using inbuilt function 'find'
	if (find(v.begin(), v.end(), key) != v.end())
		cout << key << " is present in the array";
	else
		cout << key << " is not present in the array";
	return 0;
}

JAVA

/*package whatever // do not write package name here */

import java.io.*;
import java.util.Arrays;

class GFG {
	public static void main(String[] args)
	{
		Integer arr[] = { 10, 25, 15, 12, 14 };
		int key = 15;

		// Using inbuilt function 'contains'
		boolean found = Arrays.asList(arr).contains(key);
		if (found == true) {
			System.out.println(
				key + " is present in the array");
		}
		else {
			System.out.println(
				key + " is not present in the array");
		}
	}
}

Python3

if __name__ == '__main__':
	arr = [10, 25, 15, 12, 14]
	key = 15
	found = False
	
	if key in arr:
		found = True
		
	if found == True:
		print(key, end = " is present in the array")
	else:
		print(key, end = " is not present in the array")

c#

// C# Code fpr above approach
using System;

public class GFG {
	public static void Main(string[] args)
	{
		int []arr = { 10, 25, 15, 12, 14 };
		int key = 15;

		// Using inbuilt function 'contains'
		bool found = Array.Exists(arr, x => x == key);
		if (found == true) {
			Console.WriteLine(key + " is present in the array");
		}
		else {
			Console.WriteLine(key + " is not present in the array");
		}
	}
}

// This code is contributed by AnkThon

PHP

<?php
	$arr = array(10, 25, 15, 12, 14);
	$key = 15;
	if (in_array("$key", $arr)){
		echo "$key is present in the array";
	}
	else{
		echo "$key is not present in the array";
	}
?>

Javascript

<script>
	const arr = [10, 25, 15, 12, 14];
	const key = 15
	if(arr.includes(key) == true){
		console.log( key + " is present in the array");
	}
	else{
		console.log( key + " is not present in the array");
	}
</script>

输出

15 is present in the array

除了这些内置的功能,还有其他的方法可以使用,比如。