ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

给定一个数组,元素之间的区别是一个,找出“键”元素是否存在。

前开发者教程 七月15,2018

例:

数组:

{5, 6, 7, 6, 5, 4, 3, 4, 5, 6}

键:

4

输出:

The element 4 is found at the index 6.

说明:

我们可以通过逐行移动矩阵元素并搜索该元素来解决此方法。

但是我们可以有一个优化的解决方案,因为我们知道元素之间的差是1。

 

我们可以按照以下步骤操作:

取第一个元素并用给定的键减去,您将获得一个值。让我们将其存储在“ diff”变量中。

我们知道数组元素的差为1,而不是一次搜索一次,而是通过diff跳转并搜索该元素。

解决方案说明:

 

{5, 6, 7, 6, 5, 4, 3, 4, 5, 6}
Pass 1:

i=0
    arr[0] is 5 == 4 No
    i = i + (5 - 4)
    i = 1
Pass 2:

i = 1

    arr[1] is 6 == 4 No
    i = i + (6 - 4)
    i = 3
Pass 3:

i = 3
    arr[3] is 6 == 4 No
    i = i + (6 - 4)
    i = 5

 

Pass 4:

i =5
    arr[5] is 4 == 4 Yes
    return i

解决方案在C:

#include<stdio.h>
#include<stdlib.h>
int search_element(int arr[], int lenght, int key)
{
	int diff;
	int itr = 0;

	while (itr < lenght)
	{
		if (arr[itr] == key)
			return itr;

		diff = abs(arr[itr] - key);

		itr += diff;
	}

	return -1; //element not found

}

int main()
{
	int arr[100] = {5, 6, 7, 6, 5, 4, 3, 4, 5, 6};

	int lenght = 10;

	int key = 4;

	int index = 0;

	index = search_element(arr, lenght, key);

	if(index >=0 )
		printf("The key is found at index %d\n", (index + 1) );
	else
		printf("Key not found\n");

	return 0;
}

 

输出:

The key is found at index 6

 

该网站上可用的教程列表:

C编程20+章C ++编程80+章
100多个编码问题数据结构和算法85+章
系统设计20+章Shell脚本编写12章
4g LTE 60+章节最常见的编码问题
5G NR 50+章Linux系统编程20+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的

    <nav id="N0ss6EN"><thead class="uNkA66e"></thead></nav>

        <canvas id="M3d9nCb"></canvas>