魔术索引
来源:互联网 发布:数据如何脱敏 编辑:程序博客网 时间:2024/04/28 11:32
题目描述:
1、在数组A[0..n-1]中,有所谓的魔术索引,满足条件A[i]=i。给定一个升序数组,元素值各不相同,编写一个方法,判断在数组A中是否存在魔术索引。请思考一种复杂度优于o(n)的方法。
给定一个int数组A和int n代表数组大小,请返回一个bool,代表是否存在魔术索引。
- 测试样例:[1,2,3,4,5]
- 返回:false
思路:遍历数组,时间复杂度O(n),要求复杂度优于o(n),使用二分法
class MagicIndex {public: bool findMagicIndex(vector<int> A, int n) { int magic = magicFast(A, 0, n-1); if (magic == -1) return false; return true; } int magicFast(vector<int> A, int start, int end) { if (end < start || start < 0 || end >= A.size()) return -1; int mid = (start + end) / 2; if (mid == A[mid]) return mid; else if (mid < A[mid]) return magicFast(A, start, mid-1); else return magicFast(A, mid+1, end); }};
2、进阶
题目描述
在数组A[0..n-1]中,有所谓的魔术索引,满足条件A[i]=i。给定一个不下降序列,元素值可能相同,编写一个方法,判断在数组A中是否存在魔术索引。请思考一种复杂度优于o(n)的方法。
给定一个int数组A和int n代表数组大小,请返回一个bool,代表是否存在魔术索引。
- 测试样例:[1,1,3,4,5]
- 返回:true
思路:因为有重复元素,所以使用二分法时,中间元素左右两侧都需要查找,其中左侧以中间元素值与中间元素下标中最小值为终点,右侧以中间元素值与中间元素下标中最大值为起点。
class MagicIndex {public: bool findMagicIndex(vector<int> A, int n) { int magic = magicFast(A, 0, n-1); if (magic == -1) return false; return true; } int magicFast(vector<int> A, int start, int end) { if (end < start || start < 0 || end >= A.size()) return -1; int mid = (start + end) / 2; int midValue = A[mid]; if (mid == midValue) return mid; int leftIndex = min(mid-1, midValue); int left = magicFast(A, start, leftIndex); if (left >= 0) return left; int rightIndex = max(mid+1, midValue); int right = magicFast(A, rightIndex, end); return right; }};
阅读全文
0 0
- 魔术索引
- 魔术索引
- CCI 9.3 魔术索引
- 魔术索引I
- 魔术索引II
- 牛客网 | 魔术索引I
- 牛客网 | 魔术索引II
- 魔术索引I
- 魔术索引1
- 魔术索引2
- 魔术索引I
- 魔术索引II
- 魔术索引问题
- 魔术数的索引一
- 华为机试——魔术索引
- 魔术
- 魔术
- 魔术
- Jam的计数法
- 数据结构--向量
- kindeditor用法简介
- python 基础知识-----print多次输入不换行
- 微软为什么总招人黑?
- 魔术索引
- leetcode21. Merge Two Sorted Lists
- opencv(c++)改变图像的对比度和亮度
- Java工程师面试时,一定要避开这些错误禁区!
- Centos7和RHEL7最小安装中替换ifconfig和netstat的命令
- C语言处理二值图像并计算面积和周长
- Hbase基础架构应用
- 6.10
- You need to use a Theme.AppCompat theme (or descendant) with this activity.