数据结构之线性表定义
- 线性表定义:由n各数据元素的有序序列构成,元素可以是一个数或者一个字符,也可以是一个定义对象甚至其他复杂的信息结构体。
- 线性表的两种表示方式:顺序列表存储和链式列表存储
算法题:
- 寻找给定字符串中连续出现N次字母的始末位置的字符数组。java代码实现如下:
/**
* 算法描述:寻找连续出现n次以上的字符数组。
* 例如: ef-code : S="abbxxxyzrrrru" , number = 3
* export-code: [[3, 5], [8, 11]]
*
* @param S
* @param number
* @return List<List < Integer>>
*/
public static List<List<Integer>> largeGroupPositions(String S, int number) {
List<List<Integer>> list = new ArrayList<>();
if (S == null || number < 2 || S.length() < 3) {
return list;
}
for (int i = 0; i < S.length(); i++) {
int j = i;
while (j < S.length() && S.charAt(j) == S.charAt(i)) {
j++;
}
if (number <= j - i) {
List<Integer> temp = new ArrayList<>();
temp.add(i);
temp.add(j - 1);
list.add(temp);
}
i = j;
}
return list;
}
- 输出一个链表中的后续列表。java代码实现如下:
/**
* 链表类
*
* @author export-code
*/
public class ListNode {
int val;
ListNode next;
public ListNode(int x) {
val = x;
}
/**
* 例如:
* ef-code:head=「1,2,3,4,5,6」
* export-code: 「4,5,6」
*
* @param head
* @return
*/
public ListNode middleNode(ListNode head) {
if (head == null || head.next == null) {
return head;
}
if(head.next.next == null){
return head.next;
}
ListNode nextNode = head.next;
ListNode nextNextNode = head.next.next;
boolean flag = true;
while (flag) {
if (nextNextNode == null || nextNextNode.next == null) {
flag = false;
} else {
nextNode = nextNode.next;
nextNextNode = nextNextNode.next.next;
}
}
return nextNode;
}
/**
* 最强版本
* @param head
* @return
*/
public ListNode middleNode1(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
网友评论