在排序数组中查找数字

统计一个数字在排序数组中出现的次数。

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def GetNumberOfK(self, data, k):
 4         n = len(data)
 5         if n == 0:
 6             return 0
 7         cnt = 0
 8         find = False
 9         for i in range(n):
10             if data[i] == k:
11                 cnt += 1
12                 if not find:
13                     find = True
14             else:
15                 if find:
16                     break
17         return cnt
18         # write code here

 

方法2,使用双指针:

 1 class Solution:
 2     def search(self, nums: 'List[int]', target: int) -> int:
 3         n = len(nums)
 4         if n == 0:
 5             return 0
 6         if n == 1:
 7             return nums[0] if nums[0]==target else 0
 8         minVal = nums[0]
 9         maxVal = nums[n-1]
10         if target<minVal or target>maxVal:
11             return 0
12         else:
13             i,j = 0,n-1
14             while i<n:
15                 begin = nums[i]
16                 if begin < target:
17                     i += 1
18                 else:
19                     break
20                 
21             while j >=0:
22                 end = nums[j]
23                 if end > target:
24                     j -= 1
25                 else:
26                     break
27             if(i<j and nums[i]== target and nums[j]==target):
28                 return j-i+1
29             elif nums[i]==target or nums[j]==target:
30                 return 1
31             else:
32                 return 0

 

 

Java版代码,leetcode地址

 1 class Solution {
 2     public int search(int[] nums, int target) {
 3         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 4         int n = nums.length;
 5         for (int i = 0; i < n; i++) {
 6             int curNum = nums[i];
 7             if (map.containsKey(curNum)) {
 8                 int times = map.get(curNum).intValue();
 9                 times++;
10                 map.put(curNum, times);
11             } else {
12                 map.put(curNum, 1);
13             }
14         }
15         if (map.containsKey(target)) {
16             return map.get(target).intValue();
17         } else {
18             return 0;
19         }
20     }
21 }

 

53_2,java版代码,leetcode地址

 1 class Solution {
 2     public int missingNumber(int[] nums) {
 3         int n = nums.length;
 4         int i = 0;
 5         int j = n - 1;
 6         while (i <= j) {
 7             int mid = (i + j) / 2;
 8             int midVal = nums[mid];
 9             if (midVal == mid) {
10                 i = mid + 1;
11             } else {
12                 j = mid - 1;
13             }
14         }
15         return i;
16     }
17 }

 

posted on 2019-06-14 15:40  Sempron2800+  阅读(108)  评论(0编辑  收藏  举报