C++ 3sum complexity

前端 未结 4 1196
臣服心动
臣服心动 2021-01-24 19:57

I was trying to solve the 3 sum problem in cpp.

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the

4条回答
  •  余生分开走
    2021-01-24 20:30

    The source of extra complexity is the third loop, which brings time complexity of your code to O(n3).

    Key observation here is that once you have two numbers, the third number is fixed, so you do not need to loop around to find it: use hash table to see if it's there or not in O(1). For example, if your first loop looks at value 56 and your second loop looks at value -96, the third value must be 40 in order to yield zero total.

    If the range of numbers is reasonably small (say, -10000..10000) you can use an array instead.

    This would bring time complexity to O(n2), which should be a noticeable improvement on timing.

提交回复
热议问题