我想找到第二大数字,例如这个主题。 Get the second largest number in a list in linear time
我的问题是限制词list
,[]
,remove
,del
,min
,max
,dict
,{}
,sort
,pop
。
我没有想法获得第二大数字。然后,我希望有人建议我。
谢谢!
答案 0 :(得分:2)
我不确定我是否正确理解了您的问题,但您提到的post已经为您提供了很少的好解决方案。例如,如果您不想自己编写算法代码,请使用标准库heapq,如下所示:
import random
import heapq
random.seed(1)
el = [random.randint(1, 100) for i in range(20)]
print el
first_max, second_max = heapq.nlargest(2, el)
print "Max element is {0} and the second max {1}".format(first_max,
second_max)
答案 1 :(得分:0)
class CircleView: UIView {
let circleLayer = CAShapeLayer()
override init(frame: CGRect) {
// Use UIBezierPath as an easy way to create the CGPath for the layer.
// The path should be the entire circle.
let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
super.init(frame: frame)
// Setup the CAShapeLayer with the path, colors, and line width
self.backgroundColor = UIColor.clearColor()
circleLayer.path = circlePath.CGPath
circleLayer.fillColor = UIColor.clearColor().CGColor
circleLayer.strokeColor = UIColor.redColor().CGColor
circleLayer.lineWidth = 5.0;
// Don't draw the circle initially
circleLayer.strokeEnd = 0.0
// Add the circleLayer to the view's layer's sublayers
layer.addSublayer(circleLayer)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我认为上面的代码适用于所有情况......请尝试告诉我。
答案 2 :(得分:0)
试试这个 - >
a = [1,5,7,8,3,4,6,8,2,9]
x=-999999999999
n=999999999999
for i in a:
if i>x:
x=i
for i in a:
if x-i!=0 and x-i<n:
n=x-i
ans=i
print ans