(個人水平有限,請見諒!)
描述:
假設一個有序的數組,經過未知次數的旋轉(例如0 1 2 4 5 6 7 被旋轉成 4 5 6 7 0 1 2),從中查找一個目標值,如果存在,返回其下標,不存在,返回-1。注:假設數組無重複數字。
輸入:
輸入一個有序經過旋轉的數組和要查找的目標數字,數組中各數字用“逗號”分隔,數組和目標數字用“空格”分隔。
輸出:
一個整數,表示該目標數字的下標(不存在返回-1)。
輸入樣例:
4,5,6,7,0,1,2 6
輸出樣例:
2
代碼示例:
#include <iostream>
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
int main()
{
char line[1000001];
// 循環讀入多行數據
while (cin.getline(line, 1000000)) {
// 處理並輸出結果,務必輸出換行符
char cstr[100];
int pos = 0;
int temp;
vector<int> vec;
sscanf(line, "%s %d", cstr, &pos);
char *p = strtok(cstr, ",");
while (p)
{
sscanf(p, "%d", &temp);
vec.push_back(temp);
p = strtok(NULL,",");
}
int flag = -1;
for (int i = 0; i < vec.size(); i++)
{
if (vec[i] == pos)
flag = i;
}
cout << flag <<endl;
}
return 0;
}