在数组中查找元素第一个与最后一个的位置
2022/2/5 23:16:06
本文主要是介绍在数组中查找元素第一个与最后一个的位置,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.当数组无序时:
双指针+递归
class Solution { public int[] searchRange(int[] nums, int target) { //空数组,直接返回 if(nums.length == 0) { return new int[]{-1,-1}; } //初始左指针,指向第一个元素 int left = 0; //初试右指针,指向最后一个元素 int right = nums.length-1; //所在的位置 ans[0]:第一次出现的位置 ans[1]:最后一次出现的位置 int[] ans = new int[2]; //查找方法 search(nums,left,right,target,ans); return ans; } /** *@param arr 进行查找的数组 *@param left 左指针 *@param right 右指针 *@param target 目标数字 *@param ans 存放结果的数组 */ void search(int[] arr,int left,int right,int target,int[] ans) { if(left <= right) { if(arr[left] != target) { //若没有找到,则向右移动 search(arr,left+1,right,target,ans); }else { ans[0] = left; } if(arr[right] != target) { //若没有找到,则向左移动 search(arr,left,right-1,target,ans); }else{ ans[1] = right; } }else{ //数组中不存在目标值,返回[-1,-1] ans[0]= -1; ans[1]=-1; } } } 返回该题 力扣 LeetCode
2.数组递增时——对应力扣34
双指针遍历
class Solution { public int[] searchRange(int[] nums, int target) { if(nums.length == 0) { return new int[]{-1,-1}; } int left = 0; int right = nums.length-1; int[] ans = new int[2]; while(left <= right) { if(nums[left] < target) { left++; }else { ans[0] = left; break; } } while(left <=right) { if(nums[right] > target) { right--; }else{ ans[1] = right; break; } } if(nums[ans[0]] != target) { return new int[]{-1,-1}; } return ans; } }
结果
这篇关于在数组中查找元素第一个与最后一个的位置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)