[学习报告]《LeetCode零基础指南》(第六讲) C排序API

x33g5p2x  于2021-11-27 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(246)

第一题:912. 排序数组

不花里胡哨直接上。

  1. class Solution {
  2. public int[] sortArray(int[] arr) {
  3. Arrays.sort(arr);
  4. return arr;
  5. }}

第二题:169. 多数元素

  1. class Solution {
  2. // 摩尔投票法
  3. public int majorityElement(int[] nums) {
  4. int res = 0, count = 0;
  5. for (int i = 0; i < nums.length; i++) {
  6. if (count == 0) {
  7. res = nums[i];
  8. count++;
  9. }
  10. else {
  11. if (res == nums[i]) count++;
  12. else count--;
  13. }
  14. }
  15. return res;
  16. }
  17. }

第三题:217. 存在重复元素

  1. class Solution {
  2. public boolean containsDuplicate(int[] nums) {
  3. //比较相邻的元素是否相同即可
  4. Arrays.sort(nums);
  5. for(int i=0;i<nums.length-1;i++){
  6. if(nums[i]==nums[i+1]){
  7. return true;
  8. }
  9. }
  10. return false;
  11. }}

第四题:164. 最大间距

  1. class Solution {
  2. public int maximumGap(int[] nums) {
  3. Arrays.sort(nums);
  4. int max=0;
  5. if(nums.length==1){return 0;}
  6. for(int i=0;i<nums.length-1;i++){
  7. int count=nums[i+1]-nums[i];//一组一组赋值一组一组的比
  8. max=max>count?max:count;
  9. }
  10. return max;
  11. }
  12. }

第五题:905. 按奇偶排序数组

  1. class Solution {
  2. public int[] sortArrayByParity(int[] nums) {
  3. int len=nums.length;
  4. int []arr=new int[len];
  5. for(int i=0,j=0,k=0;i<len;i++){//奇数从后面加,偶数从前加
  6. if(nums[i]%2==0){
  7. arr[j]=nums[i];
  8. j++;
  9. }
  10. else {
  11. arr[len-1-k]=nums[i];
  12. k++;
  13. }
  14. }
  15. return arr;
  16. }
  17. }

第六题:539. 最小时间差

这题不会....看评论区的

  1. class Solution {
  2. public int findMinDifference(List<String> timePoints) {
  3. int n=timePoints.size();
  4. if(n>1440){
  5. return 0;
  6. }
  7. int[] times=new int[n];
  8. // 将时间全部转化为分钟
  9. for(int i=0;i<n;i++){
  10. String m=timePoints.get(i).substring(0,2);
  11. String s=timePoints.get(i).substring(3,5);
  12. times[i]=Integer.parseInt(m)*60+Integer.parseInt(s);
  13. }
  14. int result=Integer.MAX_VALUE;
  15. for(int i=0;i<n;i++){
  16. for(int j=i+1;j<n;j++){
  17. // 两个时间最小时间
  18. int time=Math.min(Math.abs(times[i]-times[j]),Math.abs(Math.abs(times[i]-times[j])-1440));
  19. // 所有时间最小差
  20. result=Math.min(time,result);
  21. }
  22. }
  23. return result;
  24. }
  25. }

第七题:976. 三角形的最大周长

  1. class Solution {//贪心算法
  2. public int largestPerimeter(int[] nums) {
  3. Arrays.sort(nums);
  4. for(int i = nums.length-1; i>=2;i--){
  5. if(nums[i-2] + nums[i-1] > nums[i])
  6. return (nums[i-2]+nums[i-1]+nums[i]);
  7. }
  8. return 0;
  9. }
  10. }

第八题:881. 救生艇

  1. class Solution {
  2. public int numRescueBoats(int[] people, int limit) {
  3. Arrays.sort(people);
  4. int n = people.length;
  5. int i = 0, j = n - 1;
  6. while (i < j) {
  7. if (people[j] + people[i] <= limit) {
  8. i++;//成对走
  9. }
  10. j--;
  11. }//最多次数减去成对次数
  12. return n - i;
  13. }
  14. }

相关文章