二分查找进阶——循环有序数组查找再进阶——循环有序重复数组查找
来源:互联网 发布:java多线程开启 编辑:程序博客网 时间:2024/04/29 16:13
就在昨天才刚刚写了一篇关于循环有序数组查找的函数:http://blog.csdn.net/qq_33724710/article/details/51200889
今天又发现了这道题的升级版,迫不及待的拿来和大家分享(依旧来自LeetCode):
Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?For example,
Given sorted array nums =[1,1,1,2,2,3]
,Your function should return length =
有了昨天解题的思想,这道题其实无非就是多了个重复的因素:5
, with the first five elements ofnums being1
,1
,2
,2
and3
. It doesn't matter what you leave beyond the new length.分析(《LeetCode-cpp》):
允许重复元素,那么我们上一题的假设nums[mid] >= nums[first],则[first, num]递增的假设就不能成立了,比如1,3,1,1,1
如果nums[mid] >= nums[first]不能确定递增,那就把它拆分成两个条件:
1、若nums[mid] >= nums[first],则区间[first,mid]一定递增
2、若nums[mid] == nums[first],那就first++,往下一步看即可
接下来就让我们来分析下代码:
/* * leetcode, Search in Rotated Sorted Array II * Follow up for "Search in Rotated Sorted Array": * What if duplicates are allowed? * Would this affect the run-time complexity? How and why? * Write a function to determine if a given target is in the array. */#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>#define true 1#define false 0typedef int bool;bool search(int* nums, int numsSize, int target) {int first = 0;int last = numsSize - 1;/* * 与无重复的相比,不同的是,当 nums[first] <= nums[mid] 时,不能以此判断[first,mid]是递增的 * 所以当 nums[first] = nums[mid] 时,++first,跳过一个重复的数,继续循环判断, * 直到nums[first] != nums[mid],此时的情况就与无重复的有序数组相同了 */while (first <= last) {int mid = (last - first) / 2 + first;if (*(nums + mid) == target)return true;else if (*(nums + first) < *(nums + mid)) {if (*(nums + first) <= target && *(nums + mid) > target)last = mid - 1;elsefirst = mid + 1;}else if (*(nums + first) > *(nums + mid)) {if (*(nums + last) >= target && *(nums + mid) < target)first = mid + 1;elselast = mid - 1;}else { //跳过一个重复的数++first;}}return false;}int main(){int arr[] = { 1, 3, 1, 1, 1 };int sz = sizeof(arr) / sizeof(arr[0]);bool ret = search(arr, sz, 1);if (ret == true)printf("true\n");elseprintf("false\n");system("pause");return 0;}有了上一题的思路,这道题是不是也不难呢?
1 0
- 二分查找进阶——循环有序数组查找再进阶——循环有序重复数组查找
- 循环有序数组查找
- 有序 循环数组的二分查找
- 循环有序数组查找问题
- 循环有序数组的查找
- 循环有序数组查找值
- 有序(循环)数组查找元素-二分查找法
- 二分数组的扩展:二分查找循环有序数组
- 循环有序数组/旋转数组的二分查找
- 有序循环数组查找(无重复、有重复)
- 有序数组\二分查找
- 有序数组二分查找
- 循环有序数组查找一个数
- 循环有序数组的查找笔记
- 查找循环有序数组的元素
- 循环有序数组中查找指定值
- KT学算法(二)——循环有序数组查找指定元素
- 有序数组中的二分查找
- LIBCURL.LIB
- yii2 gridview 是否显示某列案例
- 2016年4月21日 21:18:25 我的第一篇博客~
- 图片超链接
- Android NDK开发C语言部分的单步跟踪
- 二分查找进阶——循环有序数组查找再进阶——循环有序重复数组查找
- maven 跳过单元测试
- Android隐藏以及显示软键盘以及不自动弹出键盘的方法
- shell中变量的空格替换
- stl erase iterator
- 堆排序
- iOS Xcode 获取项目版本号
- 通过web.xml文件自动启动spring容器加载对应的配置文件
- 注意事项·好东西·黑科技