1. /**
    2. * 35. 搜索插入位置 -> 二分查询
    3. *
    4. * @param nums
    5. * @param target
    6. * @return
    7. */
    8. public static int searchInsert(int[] nums, int target) {
    9. for (int i = 0; i < nums.length; i++) {
    10. if (nums[i] == target) {
    11. return i;
    12. } else if (nums[i] >= target) {
    13. return i;
    14. }
    15. if (i == nums.length - 1 && target > nums[i]) {
    16. return nums.length;
    17. }
    18. }
    19. return 0;
    20. }
    21. /**
    22. * 二分查找
    23. *
    24. * @param nums
    25. * @param target
    26. * @return
    27. */
    28. public static int searchInsertInGF(int[] nums, int target) {
    29. int n = nums.length;
    30. int left = 0, right = n - 1, ans = n;
    31. while (left <= right) {
    32. int mid = ((right - left) >> 1) + left;
    33. if (target <= nums[mid]) {
    34. ans = mid;
    35. right = mid - 1;
    36. } else {
    37. left = mid + 1;
    38. }
    39. }
    40. return ans;
    41. }
    42. /**
    43. * 28. 实现 strStr() 函数
    44. * <p>
    45. * 来源:力扣(LeetCode)
    46. * 链接:https://leetcode-cn.com/problems/implement-strstr
    47. * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    48. *
    49. * @param haystack
    50. * @param needle
    51. * @return
    52. */
    53. public static int strStr(String haystack, String needle) {
    54. if (null == needle || 0 == needle.length()) {
    55. return 0;
    56. }
    57. return haystack.indexOf(needle);
    58. }
    59. /**
    60. * 27. 移除元素
    61. *
    62. * @param nums
    63. * @param val
    64. * @return
    65. */
    66. public static int removeElement(int[] nums, int val) {
    67. int slow = 0;
    68. for (int i = 0; i < nums.length; i++) {
    69. if (nums[i] != val) {
    70. nums[slow++] = nums[i];
    71. }
    72. }
    73. return slow;
    74. }
    75. /**
    76. * 26. 删除有序数组中的重复项
    77. *
    78. * @param nums
    79. * @return
    80. */
    81. public static int removeDuplicates(int[] nums) {
    82. if (nums.length == 0 || nums.length == 1) {
    83. return nums.length;
    84. }
    85. int slow = 0;
    86. for (int i = 0; i < nums.length; i++) {
    87. if (i != 0 && nums[i] != nums[slow]) {
    88. nums[++slow] = nums[i];
    89. }
    90. }
    91. return slow + 1;
    92. }