微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

该代码有效...但是为什么呢? 将数字插入已排序的数组中

如何解决该代码有效...但是为什么呢? 将数字插入已排序的数组中

代码的目的是在数组中插入一个数字,该数字应首先按升序排序。代码应返回该数字在排序数组中所属的索引。

很简单,但是解决一个示例的方法使我感到困惑:

In [17]:  print(len(connection.queries))
7

In [18]: class UserSerializer(serializers.ModelSerializer):
    ...:     email = serializers.EmailField()
    ...: 
    ...:     def validate_email(self,value):
    ...:         lower_email = value.lower()
    ...:         if User.objects.filter(email__iexact=lower_email).exists():
    ...:             raise serializers.ValidationError("Duplicate")
    ...:         return lower_email
    ...: 
    ...:     class Meta:
    ...:         model = User
    ...:         fields = ('email',)
    ...: 

In [19]: print(len(connection.queries))
7

In [20]: s = UserSerializer(data={'email': 'Foo@gmail.com'})

In [21]: print(len(connection.queries))
7

In [22]: try:
    ...:     s.is_valid(True)
    ...: except serializers.ValidationError:
    ...:     print("raised validation error")
    ...: 
raised validation error

In [23]: print(len(connection.queries))
8

代码有效,但是我不明白为什么最后使用 return arr.length; 会导致我们需要该索引。那不应该给我们完整的祈祷的实际长度吗?为什么它会导致插入数字的索引应该是

谢谢!

解决方法

仅当num大于原始数组中的每个元素时,该函数才返回数组的长度。在这种情况下,我们新排序的数组的长度应为arr.length+1,而num应该是最后一个元素,索引为arr.length

,

for循环未找到较小的a来插入元素时,最后可能的解决方法是arr.length

arr                arr.length      insert(arr.length,"X")
-------------------------------------------------------------
[]                 0               ["X"]
["A"]              1               ["A","X"]
["A","B"]         2               ["A","B","C"]    3               ["A","C","X"]
...
,

该功能正常-可能在这里或那里进行了调整:

def keyPressEvent(self,event: QtGui.QKeyEvent):
    if event.key() == Qt.Key_Return:  # 16777220 # Enter
        col = self.currentColumn()
        row = self.currentRow()
        self.setCurrentCell(row + 1,col)

看起来令人困惑的是,您期望每次调用函数时都会发生 return arr.length 。仅当数组中的任何值都不大于参数 num 值时,才会发生这种情况。如果发现一个大于该数字的数字,则会插入 return a 行并立即结束函数的执行,因此不会达到 return arr.length 。您可以在此代码段中看到这一点,因为我已将 num 值设置为10000。当然,您实际上不需要对数组进行排序即可找到大于的第一个数字。 num

更新:这是我的操作方式(除了我将在此功能之外使用排序功能):

let array = [1028,64,16,32,8,256,128];

function getIndexToIns(arr,num) {
  arr.sort(function(a,b) {
    return a - b;
  });

  for (var a = 0; a < arr.length; a++) {
    if (arr[a] >= num) {
      return a;
    }
  }
  return arr.length;
}

console.log(getIndexToIns(array,10000));

通过这种方式可以清楚地了解正在发生的事情以及我们期望返回的值-function getIndexToInsert(arr,b) { return a - b; }); let result = -1; for (var a = 0; a < arr.length; a++) { if (arr[a] >= num) { // if we have found a number greater than num,set the result to the current index position and break out of the for loop result = a; break; } } // now we have either -1 (not found) or a number >= 0 (index of item found) return result; } let newvalue = 547; let pos = getIndexToInsert(array,newvalue); // now test the result if (pos == -1) { // no existing value is greater than newvalue,so pos remained as -1 // so,just add newvalue to the end of the array array.push(newvalue); } else { // otherwise,we have the index number of the first value that is > newvalue // so,insert the newvalue there instead array.splice(pos,newvalue); } console.log(array); 或索引位置。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。