2018年貝殼網校招(秋招)演算法筆試程式設計題
阿新 • • 發佈:2019-01-11
1、題目描述:
給定一個長度為N的序列A1到AN,求所有區間[L,R](1≤L≤R≤N)的極差之和,其中區間[L,R]的極差定義為AL到AR中的最大值與最小值之差。
思路:暴力求解,通過率36%
程式碼如下:
# -*- coding:utf-8 -*- class Solution: # array 二維列表 def Find(self, N, array): # write code here num = 0 for i in range(N-1): for j in range(i+1,N): num += (max(array[i:j+1]) - min(array[i:j+1])) return num while (True): try: n = input() array = input() N = int(n) arr = array.split(' ') for i in range(N): arr[i] = eval(arr[i]) s = Solution() num = s.Find(N,arr) print(num) except: break
2、題目描述:
眾所周知,新款膝上型電腦都擁有自己的省電方案,現有某品牌膝上型電腦,正常工作狀態下耗電量為P1/min,當機主離開電腦T1min時,電腦進入螢幕保護狀態,耗電量為P2/min,當電腦進入屏保狀態T2min後,電腦進入睡眠狀態,耗電量為P3/min。
已知電腦主人的一天有n段時間在使用電腦工作,即[l1, r1], [l2, r2],…, [ln, rn],在[rn-1, ln]期間是沒有操作電腦的,問在[l1, rn]時間內,電腦共耗電多少瓦。、
思路:沒啥好說的,分段函式求解,通過率100%
程式碼如下:
# -*- coding:utf-8 -*- class Solution: # array 二維列表 def Find(self, arr, ran): # write code here n, p1, p2, p3, t1, t2 = arr[0],arr[1],arr[2],arr[3],arr[4],arr[5] num1 = s.ran_nei(ran,p1) num2 = s.ran_wai(ran, t1, t2, p1, p2, p3) return (num1+num2) def ran_nei(self,ran,p): score = 0 for i in range(len(ran)): score += (ran[i][1] - ran[i][0])*p return score def ran_wai(self,ran,t1,t2,p1,p2,p3): score = 0 for i in range(len(ran)-1): sub_ran = ran[i+1][0] - ran[i][1] if sub_ran <= t1: score += sub_ran*p1 elif t1 < sub_ran <= (t2+t1): score += (t1*p1 + (sub_ran-t1)*p2) elif sub_ran > (t2+t1): score += (t1*p1 +t2*p2 + (sub_ran-t2-t1)*p3) return score while (True): try: ran = [] array = input() arr = array.split(' ') for i in range(len(arr)): arr[i] = eval(arr[i]) for i in range(arr[0]): a = input() b = a.split(' ') c,d = eval(b[0]),eval(b[1]) ran.append([c,d]) s = Solution() num = s.Find(arr,ran) print(num) except: break
3、題目描述:
撲克牌分別為A23456789TJQK共13張牌
出牌規則如下:
單牌,對子,三帶至多一張牌,四帶至多兩張牌,連續至少五張為順子
輸入:一個長度為20的字串,例如‘8K67A65K27T59K346AK2’
輸出:至少多少輪能把手裡的牌出完
思路:暫時只想起將輸入的字串挨個放入健排序的字典中,對字典的健可以進行排序(找順子),以及每個健(對應牌值)底下有幾張牌(找四帶二,三帶一,對子,單牌),繼而算出至少多少輪出完
程式碼如下(暫時只實現字串讀取進字典):
# -*- coding:utf-8 -*- class Solution: # array 二維列表 def Find(self, array): # write code here return 4 while (True): try: dic = {} arr = input() print(arr) a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13 = [],[],[],[],[],[],[],[],[],[],[],[],[] for i in range(len(arr)): if arr[i] == 'A': a1.append(arr[i]) elif arr[i] == '2': a2.append(arr[i]) elif arr[i] == '3': a3.append(arr[i]) elif arr[i] == '4': a4.append(arr[i]) elif arr[i] == '5': a5.append(arr[i]) elif arr[i] == '6': a6.append(arr[i]) elif arr[i] == '7': a7.append(arr[i]) elif arr[i] == '8': a8.append(arr[i]) elif arr[i] == '9': a9.append(arr[i]) elif arr[i] == 'T': a10.append(arr[i]) elif arr[i] == 'J': a11.append(arr[i]) elif arr[i] == 'Q': a12.append(arr[i]) elif arr[i] == 'K': a13.append(arr[i]) dic[1], dic[2], dic[3], dic[4], dic[5], dic[6], dic[7], dic[8], dic[9], dic[10], dic[11], dic[12], dic[13] = a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13 s = Solution() num = s.Find(dic) print(num) except: break