Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1750426
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2018-04-08 11:36:49

最近看了点视频,用代码记录下,今天是Array.

1. find the most frequently occurred item in an Array

思路很简单,就是用词典来记录item出现的次数就可以,key 是item, value是item出现的次数。
注意处理有多个item同时有最高的出现次数就可以了。 

点击(此处)折叠或打开

  1. def most_frequent(given_array):
  2.     most_count = -1
  3.     max_item = None

  4.     count ={}
  5.     
  6.     for item in given_array:
  7.         if item in count:
  8.             count[item] += 1
  9.         else:
  10.             count[item] = 1
  11.     """
  12.         if count[item] > most_count:
  13.             max_item = item
  14.             most_count = count[item]
  15.     #return (max_item,most_count)
  16.     """
  17.     #if there is more than 1 item
  18.     max_value = max(count.values())
  19.     
  20.     return [(i,count[i]) for i in count if count[i] == max_value]
  21.     

  22. ll=[1,2,4,5,7,1,2,2,2,2,1,1,1]
  23. print(most_frequent(ll))

2. 

Find two common elements in 2 sorted Arrays

在两个已经排序的数组里面找到相同的element.

点击(此处)折叠或打开

  1. def common_elem(A,B):
  2.     p1=0
  3.     p2=0
  4.     result = [] #List for Python and ArrayList for Java
  5.     while p1 < len(A) and p2 < len(B):
  6.         if A[p1] == B[p2]:
  7.             result.append(A[p1])
  8.             p1 += 1
  9.             p2 += 1
  10.         elif A[p1] > B[p2]:
  11.             p2 += 1
  12.         else:
  13.             p1 += 1
  14.     return result

  15. l1=[1,3,4,6,7,9]
  16. l2=[1,2,4,5,9,10]
  17. print(common_elem(l1, l2))

3.

is One Array a rotation of Another Array

前提条件:no duplicate in Array A AND Array B


点击(此处)折叠或打开

  1. def is_rotation(A, B):
  2.     if len(A) != len(B):
  3.         return False

  4.     key = A[0]
  5.     key_i= -1
  6.     
  7.     for i in range(len(B)):
  8.         if B[i] == key:
  9.             key_i = i
  10.             break
  11.     if key_i == -1:
  12.         return False

  13.     for i in range(len(A)):
  14.         j= (i+key_i) % len(A)
  15.         if A[i] != B[j]:
  16.             return False
  17.     return True

  18. la1=[1,2,3,4,5,6,7]
  19. la2=[4,5,6,7,1,2,3]

  20. print(is_rotation(la1, la2))




阅读(1075) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~