求最大值和最小值

求最大值和最小值

第一种赋值比较

  var max = Math.max(1, 2, 4, 6, 7, 1);

        var a=Math.max(1,2)
        a = Math.max(a,4)//a是上一个最大值,
        a = Math.max(a,6)
        a = Math.max(a,7)
        a = Math.max(a,1)
        console.log(max);

第二种遍历数组来比较

var arr = [1, 2, 4, 6, 7, 1];
  var max = arr[0]
        for(var i = 0;i<arr.length;i++){
          //   var max = arr[0]// bug 永远都是初始化--> 导致 第一个数于最后一个数组比较大小
            max = Math.max(max,arr[i])
        }
        console.log(max);

第三种使用reduce来比较

 var arr = [1, 2, 4, 6, 7, 1];
ar max = arr.reduce(function(pre,next){
          console.log(pre,next)
            return Math.max(pre,next)
        });
        console.log(max);

第四种利用排序

var arr1 = [10,101,56, 2, 4, 6, 7, 1];
      // sort() 排序
      // 参数 函数
      arr1.sort(function(a,b){
          // a-b 升序
          // b-a 降序
          // 注意 number类型排序,如果是字符串,更具第一个字符的编码值大小进行排序 
          return a-b
      })
      var max = arr1[arr.length-1]
      console.log(arr1);

第五中es6中,很取巧

  var arr2 = [10,101,56, 2, 4, 6, 7, 1];
      var max1 =  Math.max(...arr2);
      console.log(max1);

函数封装

 var arr = [1, 2, 4, 6, 7, 1];
      function min(){
        var min = arr[0];//这是第一个值
        arr.forEach(function(item){
          min = Math.max(min,item)//是那第一个值跟他们后面的比较
        })
        return min
      }
      console.log(min())

写的不好,请见谅

### 使用单链表实现最大值最小值 对于单链表而言,可以采用线性扫描的方式找到其中的最大值最小值。下面分别介绍这种操作的具体方法。 #### 查找单链表中的最小值 为了查找单链表中的最小值,可以从头节点开始遍历整个列表,在此过程中维护一个变量用于存储当前遇到的最小值以及对应的节点位置。初始时将第一个有效节点设为最小值候选者;随后继续向后访问其他节点并与已知最小值对比更新之直到结束为止[^1]。 ```c // 定义链表结构体 typedef struct ListNode { int data; struct ListNode *next; } LNode; void findMin(LinkList L, int *minValue) { if (!L || !L->next) return; // 如果为空链表则直接返回 LNode *current = L->next; // 跳过头结点 *minValue = current->data; // 初始化最小值为首个实际元素 while (current != NULL) { if (*minValue > current->data) *minValue = current->data; current = current->next; } } ``` #### 查找单链表中的最大值 同样的思路也适用于寻找最大值的情况——只需改变比较条件即可。即初始化最大值为第一个真实存在的数值项之后依次考察剩余各成员并适时调整极大值记录直至完成全部检验工作。 ```c void findMax(LinkList L, int *maxValue) { if (!L || !L->next) return; // 若为空链表,则不执行任何动作 LNode *current = L->next; // 排除头部哨兵位 *maxValue = current->data; // 设定起始参照标准 while (current != NULL){ if(*maxValue < current->data) *maxValue = current->data; current = current->next; } } ``` 上述个函数均实现了O(n)的时间复杂度,这里n代表链表长度。这表明无论是在最坏还是平均情况下都需要对每一个节点做一次处理才能得出最终的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值