496. Next Greater Element I
来源:互联网 发布:审批工作流数据库设计 编辑:程序博客网 时间:2024/06/07 00:31
问题: You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
问题描述: 题目给出了两个无重复元素的数组nums1,nums2,其中nums1是nums2的子数组。要求得到一个长度与nums1相同,并且由与nums1元素对应的nums2元素的下一个较大元素所组成的数组,若不存在比子数组元素大的情况返回-1。
个人解题思路:1.定位元素相同的数组位置。2. 查找第一个大于所要查找元素的值,否则返回-1。一开始想图方便用Array.sort(int[] nums)与Array.binarySearch(int[] nums,int key),利用排序和查找方法来定位值出现位置,却忽略了此时经过排序后的数组,其元素顺序已经改变。
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { for( int i = 0; i < nums1.length; ++i){ int j = 0; for(;j < nums2.length; ++j){//若在循环体中定义j,则是循环中的局部变量,退出循环时,这个变量会被回收。 if(nums2[j] == nums1[i]) break;//定位相等位置 } int exch = nums1[i]; nums1[i] = -1; for(++j; j < nums2.length; ++j){ if(nums2[j] > exch){//出现了直接用nums2[j] >nums2[j-1] 的错误,忽略了j在变化。 nums1[i] = nums2[j]; break; } } } return nums1; }}
运行时间为14ms,运行速度较慢。
范例解决方法:
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { if(nums1.length == 0) return new int[]{}; int[] res = new int[nums1.length]; int max = Integer.MIN_VALUE; for(int num : nums2){ if(max < num) max = num; } int[] map = new int[max + 1]; Arrays.fill(map, -1); for(int i = 0 ; i < nums2.length ; i ++){ map[nums2[i]] = i; } for(int i = 0 ; i < nums1.length ; i ++){ if(nums1[i] >= max) res[i] = -1; else{ int index = map[nums1[i]]; while(++index < nums2.length){ if(nums2[index] > nums1[i]){ res[i] = nums2[index]; break; } } if(res[i] == 0) res[i] = -1; } } return res; }}
阅读全文
0 0
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496.Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 8.4桶排序
- vue2+axios 增删改查
- Linux 根目录介绍
- 浅谈小程序
- Android点击事件分发
- 496. Next Greater Element I
- 《Spring Boot in Action》【2. 开发第一个应用】
- ArcGIS水文分析实战教程(15)库容和淹没区计算
- centos 安装php7 redis扩展
- matplotlib--3d显示
- Unreal 后期处理材质范例
- 《基于R语言的自动数据收集》--第3章 XML和JSON
- Java并发编程:同步容器
- 详细的JDK安装方式 java开发环境搭建之JDK配置