面试简单算法题

5 阅读1分钟

1.冒泡排序

public class BubbleSort { 
public static void main(String[] args) { 
int[] arr = {5, 2, 8, 1, 3}; 
// 冒泡排序 
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) { 
if (arr[j] > arr[j + 1]) { 
// 交换 
int temp = arr[j]; 
arr[j] = arr[j + 1]; 
arr[j + 1] = temp; 
} 
} 
} 
// 输出结果
for (int num : arr) { 
System.out.print(num + " "); 
}
}
}

2.二分查找

public class BinarySearch { 
public static int binarySearch(int[] arr, int target) {
int left = 0; 
int right = arr.length - 1;
while (left <= right) { 
int mid = (left + right) / 2;
if (arr[mid] == target) { 
return mid; // 找到,返回下标 
} else if (arr[mid] < target) { 
left = mid + 1;
} else { 
right = mid - 1; 
} 
} 
return -1; // 没找到
} 
public static void main(String[] args) { 
int[] arr = {1,3,5,7,9,11}; 
System.out.println(binarySearch(arr, 7)); // 输出 3
} 
}

3.反转链表

class ListNode { 
int val; 
ListNode next;
ListNode(int val) { this.val = val; } 
} 
public class ReverseList { 
public ListNode reverseList(ListNode head) { 
ListNode pre = null; 
ListNode cur = head; 
while (cur != null) {
ListNode next = cur.next; 
cur.next = pre;
pre = cur;
cur = next; 
} 
return pre; 
} 
}

4.两数之和

public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(); 
for (int i = 0; i < nums.length; i++) { 
int another = target - nums[i]; 
if (map.containsKey(another)) {
return new int[]{map.get(another), i}; 
}
map.put(nums[i], i);
} 
return new int[0]; 
}

5.斐波那契数列

// 求第 n 项(递归) 
public static int fib(int n) { 
if (n <= 2) return 1;
return fib(n - 1) + fib(n - 2); 
}
// 循环版(效率高,推荐) 
public static int fibLoop(int n) { 
if (n <= 2) return 1; 
int a = 1, b = 1; 
for (int i = 3; i <= n; i++) { 
int c = a + b; 
a = b; b = c; 
} 
return b; 
}