Q330. Patching Array (Hard)
We have to check every number from 1 ~ n miss: Int
We should keep an index pointer to record if we have checked all the number within the array index:Int
We have to loop until miss == n
Everytime we should compare if all the elements have been used
If not all used
Then compare if miss >= nums[index]
YES: we've covered [1, miss - 1], since nums[index] is also smaller that miss, the whole range has been covered is [1, miss - 1 + nums[index]], we can update miss
NO: have to insert miss, [1, miss * 2 - 1] will be covered by the sum of the elements in array, so update miss = miss * 2
If all used: insert miss then, [1, miss * 2 - 1] will be covered by the sum of the elements in array, so update miss = miss * 2
https://github.com/Sylvia-YiyinShen/Algorithm/blob/master/Greedy/Q330.PatchingArray.playground/Contents.swift
No comments:
Post a Comment