代码随想录算法训练营第一天|704.二分查找、27.移除元素

49 阅读1分钟

t.csdnimg.cn/WAGBU

前言

习惯写dart,不经常写java

列表的表示方式有不同,dart直接中括号,java还要new int[]{}

写不习惯

LeetCode 704

思路总结

想都没想就想着用双指针了,因为按顺序的只要找到就返回,没找到就return -1

public class TwoSearch {
    public static void main(String[] args) {
        int[] nums = new int[]{-1, 0, 3, 5, 9, 12};
        Solution1 solution1 = new Solution1();
        System.out.println(solution1.search(nums, 9));
    }
}

class Solution1 {
    public int search(int[] nums, int target) {
        int last = nums.length;
        int pre = 0;
        while (pre < last) {
            if (nums[pre] == target) {
                return pre;
            }
            if (nums[last - 1] == target) {
                return last - 1;
            }
            pre++;
            last--;
        }
        return -1;
    }
}
void main() {
  int twoSearch(List nums, int target) {
    int last = nums.length;
    int pre = 0;
    while (pre < last) {
      if (target == nums[pre]) {
        return pre;
      }
      if (target == nums[last - 1]) {
        return last - 1;
      }
      pre++;
      last--;
    }
    return -1;
  }

  print(twoSearch([5], 5));
}

LeetCode 27

思路总结

这题是双指针,但前面一直没看懂,题目意思

for循环的时候犯了个错误,i < 数据长度,结果直接返回出来值有问题,用leetcode上面的编译器真的很难debug

最后不仅要return数组的长度,还要改变数组,题目没审好

import java.util.Arrays;

public class RemoveElement {
    public static void main(String[] args) {
        System.out.println(solute(new int[]{2, 3, 4, 3, 2}, 3));
    }

    static int solute(int[] nums, int val) {
        int length = nums.length;

        // 第一眼 想着新建一个数组插入数据,return的
        // 结果发现只要return 慢指针的数值就行
        //int[] array = new int[nums.length];

        int quick = 0;
        int slow = 0;

        for (int i = 0; i < length; i++) {
            if (nums[quick] != val) {
                nums[slow] = nums[quick];
                slow++;
            }
            quick++;
        }
        System.out.println(Arrays.toString(nums));
        return slow;
    }
}