为什么这段代码在Go O(n²)中而不是O(n)中?

时间:2019-07-23 11:37:04

标签: go time-complexity

我正在阅读Effective Go的过程中,有一段代码我认为是O(n)的复杂性,但却是O(n²)。为什么将此for range循环视为O(n²)

找到了here (under #interfaces)

type Sequence []int
...
func (s Sequence) String() string {
    ...
    for i, elem := range s { // Loop is O(N²); will fix that in next example.
        if i > 0 {
            str += " "
        }
        str += fmt.Sprint(elem)
    }
    ...
}

我认为它是O(n)的原因是因为s上只有一个迭代,并且if语句和fmt.Sprint不应在{{1}中}。

1 个答案:

答案 0 :(得分:6)

每次连接str += fmt.Sprint(elem)时,您都会创建一个新的String,该str必须将上一个n(n+1)/2的字符转移(复制)到新字符中。在步骤1中,您复制1个字符,在步骤2、2中,依此类推。这将得到O(n^2)个副本。因此,复杂度为var aa = '<?xml version = "1.0" encoding = "UTF-8"?><imsx_POXEnvelopeRequest xmlns="'+req.body.lis_outcome_service_url+'"> <imsx_POXHeader> <imsx_POXRequestHeaderInfo> <imsx_version>V1.0</imsx_version> <imsx_messageIdentifier>999999123</imsx_messageIdentifier> </imsx_POXRequestHeaderInfo> </imsx_POXHeader> <imsx_POXBody> <replaceResultRequest> <resultRecord> <sourcedGUID> <sourcedId>3124567</sourcedId> </sourcedGUID> <result> <resultScore> <language>en</language> <textString>0.92</textString> </resultScore> <!-- Added element --> <resultData> <text>text data for anvas submission</text> </resultData> </result> </resultRecord> </replaceResultRequest> </imsx_POXBody></imsx_POXEnvelopeRequest>'; var request = require('request'); request.post({ headers: {'content-type' : 'application/x-www-form-urlencoded'}, url: req.body.lis_outcome_service_url, form: {param1:aa} }, function(error, response, body){ console.log(body); });