[关闭]
@XQF 2018-03-07T22:57:47.000000Z 字数 1036 阅读 1107

如何求指定数字在数组中第一次出现的位置?

数据结构与算法


问题描述:给定数组a={3,4,5,6,7,8,9,8},这个数组中相邻元素之差都为1,给定数字9,他在数组中第一次出现的位置?

1.爆破模式---暴力破解

也就是最简单的遍历了,。

2.跳跃式搜索

那就是利用题中的相邻之差为1,根据题意看出是绝对值。
突破口就是数组的第一个元素。利用示例,给出的数字为9,那么我就马上去查看index=9-nums[0]的位置。因为假如数组递增的话这个位置就解决问题了,假如不是递增,那么,。,。该目标数一定会在这个新的index后面。。。中间的index就可以跳过不查了

第一发跳跃式,。,。,只跳跃了几个

  1. public int findIndex(int[] nums, int target) {
  2. if (nums == null || nums.length == 0) {
  3. return -1;
  4. }
  5. int index = 0;
  6. if (target != nums[0]) {
  7. if (target > nums[0]) {
  8. index = target - nums[0];
  9. } else if (target < nums[0]) {
  10. index = nums[0] - target;
  11. }
  12. for (int i = index; i < nums.length; i++) {
  13. if (nums[i] == target) {
  14. return i;
  15. }
  16. }
  17. }
  18. return 0;
  19. }

第二发跳跃式

  1. public class Solution {
  2. public int findIndex(int[] nums, int target) {
  3. if (nums == null || nums.length == 0) {
  4. return -1;
  5. }
  6. int index = 0;
  7. while (target != nums[index]) {
  8. if (target > nums[index]) {
  9. index = target - nums[index];
  10. } else if (target < nums[index]) {
  11. index = nums[index] - target;
  12. }
  13. }
  14. return index;
  15. }
  16. public static void main(String[] args) {
  17. Solution solution = new Solution();
  18. int[] nums = {4, 5, 6, 4, 5, 7, 9, 0};
  19. int result = solution.findIndex(nums, 5);
  20. System.out.println("result:" + result);
  21. }
  22. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注