• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

Data Structure Array: Find the minimum distance between two numbers

http://www.geeksforgeeks.org/find-the-minimum-distance-between-two-numbers/

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <queue>
 5 #include <stack>
 6 #include <string>
 7 #include <fstream>
 8 #include <map>
 9 using namespace std;
10 
11 int mindis(int arr[], int n, int x, int y) {
12     int pre = 0;
13     while (arr[pre] != x && arr[pre] != y) pre++;
14     int i = pre + 1;
15     int ans = n;
16     for (; i < n; i++) {
17         if (arr[i] != x && arr[i] != y) continue;
18         if (arr[i] != arr[pre]) ans = min(ans, i - pre);
19         pre = i;
20     }
21     return ans;
22 }
23 
24 int main() {
25     int arr[12] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3};
26     cout << mindis(arr, 12, 3, 6) << endl;
27     return 0;
28 }

 

posted @ 2014-04-08 13:01  ying_vincent  阅读(140)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3