codewars——Pick peaks

In this kata, you will write a function that returns the positions and the values of the “peaks” (or local maxima) of a numeric array.For example, the array arr = [0, 1, 2, 5, 1, 0] has a peak at position 3 with a value of 5 (since arr[3] equals 5).The output will be returned as an object of type PeakData which has two members: pos and peaks. Both of these members should be vectors. If there is no peak in the given array then the output should be a PeakData with an empty vector for both the pos and peaks members.PeakData is defined in Preloaded as follows:struct PeakData {
vector pos, peaks;
};Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3]) should return {pos: [3, 7], peaks: [6, 3]} (or equivalent in other languages)All input arrays will be valid integer arrays (although it could still be empty), so you won’t need to validate the input.The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don’t know what is after and before and therefore, we don’t know if it is a peak or not).Also, beware of plateaus !!! [1, 2, 2, 2, 1] has a peak while [1, 2, 2, 2, 3]does not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example: pickPeaks([1, 2, 2, 2, 1]) returns {pos: [1], peaks: [2]} (or equivalent in other languages)Have fun!

例如,數組arr=[0,1,2,5,1,0]在位置3處有一個峯值,值爲5(因爲arr[3]等於5)。
輸出將作爲peakdata類型的對象返回,peakdata有兩個成員:pos和peaks。這兩個成員都應該是向量s。如果給定數組中沒有峯值,那麼輸出應該是一個峯值數據,pos和peaks成員都有一個空向量。
峯值數據在預加載中定義如下:
結構峯值數據{
向量pos,峯值;
};
示例:pickpeaks([3、2、3、6、4、1、2、3、2、1、2、3])應返回pos:[3、7],peaks:[6、3](或其他語言中的等效值)
所有輸入數組都將是有效的整數數組(儘管它可能仍然爲空),因此您不需要驗證輸入。
數組的第一個和最後一個元素不會被視爲峯值(在數學函數的上下文中,我們不知道什麼在後面和前面,因此我們不知道它是否是峯值)。
同時,小心高原!!!![1,2,2,2,1]有峯值,而[1,2,2,3]沒有。如果出現高原峯值,請只返回高原起點的位置和值。例如:pickpeaks([1,2,2,1])返回pos:[1],peaks:[2](或其他語言中的等效值)
玩得高興!

我的思路

我的思路是這樣的哈:

  1. 遍歷數組,設定一個起始的key值,初始值爲0,當每個值比左邊的大,就+1,比右邊的小呢就再+1,當值爲2時返回。每次循環結束,把key重置爲0
  2. 上面的算法實現了返回部分峯值,即一個數左右兩邊都比他小的這種情況,沒有考慮右邊的數與他相等。題目要求返回峯值的第一個index
  3. 因此,我設置count的值,只要右邊的數和它本身相等,那就設定count+1,直到出現第比他還小的數,這個時候i - count就是第一次出現的數字咯。
def pick_peaks(arr):
    dic = dict()
    dic['pos'] = list()
    dic['peaks'] = list()
    key = 0
    count = 0
    for i in range(1, len(arr)-1):
        if arr[i] > arr[i-1]:
            key += 1
        if arr[i] > arr[i+1]:
            key += 1
        if arr[i] == arr[i+1]:
            count += 1
            continue
        if key == 2:
            dic['pos'].append(i-count)
            dic['peaks'].append(arr[i])
        key = 0
        count = 0
    print(dic)
    return dic

我的總結

本來想用C++來做,練習C++,後來發現C++的話,我連題目都看不懂,所以改爲python了。做出來就好,做出來就好。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章