在未排序的序列中查找缺失的数字

时间:2017-01-09 16:01:37

标签: java string numbers character complexity-theory

我必须在未排序的序列中找到缺失的数字。此序列存储在String对象中。例如,在此序列中:3 1 6 5 2缺少的数字为4。 在每个数字之间有一个\n。我必须在不使用数组,字典,列表等结构的情况下执行此操作,因为我需要具有O(1)复杂度。 在输入中,我还接收序列的最大数量(在示例序列中,我收到数字6) 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

方法1(使用和公式) 算法:

  
      
  1. 获取数字总和      total = n *(n + 1)/ 2 ----------- O(1)
  2.         
        

    2从sum和中减去所有数字        你会得到遗失的号码

      
 void ans(int total){     ///O(1)

            big_total = (n+1)*(n+2)/2;  //  n+1 because 1 number is missing

            return (big_total-total);


     }




input_array()
{
  int n,total=0,i;

  cout<<"enter no of element";
  cin>>n;
  for(i=0;i<n;i++)
   {
     cin>>arr[i];
     total+=arr[i];
   }

   cout<<ans(total);

}
相关问题