leetcode一些题的想法

167. Two Sum II - Input array is sorted

这道题是给定一个数组和一个数字a,再数组中查找两个数其之和等于a,两个数不会取同一个数,数必定有解,数组有序。

暴力的是两层for循环,复杂度n方,然后改为了折半查找,平均复杂度是nlogn。

比较优化的是利用两个数之和的数学关系,如果这两个数小于a,必定一个数取值小了,角标增改++,如果大于a,一个数的取值大了,角标--。我列出代码(代码不是我写的,嘻嘻)

   int i = 0, j = numbers.length - 1;
        
        while(i < j) {
            int tmp = numbers[i] + numbers[j];
            
            if(tmp < target)
                i++;
            else if(tmp > target)
                j--;
            else
                break;
        }
        
        return new int[] {i + 1, j + 1};
这是我根据上面的思路改的。
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int i = 0;
        int j = numbers.length-1;
        int a = numbers[i]+numbers[j];
        while(a!=target){
            if(a>target)j--;
            else i++;
            a = numbers[i]+numbers[j];
        }
        
        int[]a1={i+1,j+1};
        return a1;
    }   
}

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.


题意:给你一个数组,让你找打一个数量超过n/2的数,假定数组非空,且这个数字必定存在

解1:这个数组排序,统计每种数字出现的次数

解2:排序,通过题意可知这个被查找的数字必定出现在nums[n/2]上,直接返回这个值就可以了

解3:(看到别的答案看到的)不需要排序,由题意知道这个数字必定会比别的数字多出至少一个,利用这个性质,在数组中删掉两个不同的数字(不是真正以上的删除),不停删除,知道剩下的数只有一个(elem)。这个数字便是我们要查找的。下面是解3的代码。

  	  int elem = 0;//要查找的那个数字
          int count = 0;//用来判断
          
          for(int i = 0; i < num.size(); i++)  {
              
             if(count == 0)  {
                 elem = num[i];
                 count = 1;
             }
             else    {
                 if(elem == num[i])
                     count++;
                 else
                     count--;
             }
             
         }
         return elem;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值