Algorithm question: Find the position where a number appears in an array, and an array of numbers

Source: Internet
Author: User

Algorithm question: Find the position where a number appears in an array, and an array of numbers

// There is an int-type array, and the difference between each two adjacent numbers is not 1, that is, //-1. Given a number, we need to find the position of this number in the array. # Include <iostream> using namespace std; void Grial (int a [], int n, int val) {// my idea is to start with the first number, if the number is 2, // and the number I want to find is 5, then it is better that I have to jump to the back and jump to the position 5-2 = 3, because each number only differs by 1 or-1. int I = 0; int * B = new int [n]; // if all values are val, n space is required. Int k = 0; for (; I <n;) {if (a [I] = val) {B [k ++] = I; I ++ ;} else {int len = a [I]> val? A [I]-val: val-a [I]; I + = len ;}} cout <val <"The subscript position displayed is :"; for (I = 0; I <k; I ++) {cout <B [I] <";}cout <endl ;}int main () {int a [] = {2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 3, 4, 5}; Grial (a, sizeof (a)/sizeof (int ), 5); return 0 ;}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.