Example 2 Let the terms of the sequence $\left\{a_{n}\right\}$ be
$$
1,1,2,2,2,2,2, \cdots, \underbrace{n, n, \cdots, n}_{(3 n-1) \uparrow}, \cdots \text {. }
$$

Find $a_{n}$ and $S_{n}$.
Solution: By the formula for the sum of an arithmetic sequence, the sum of the first $(m-1)$ segments of the sequence $a_{n}$ is
$$
\begin{array}{l}
2+5+8+\cdots+(3 m-4) \\
=\frac{1}{2}(m-1)(3 m-2) .
\end{array}
$$

It is evident that, if and only if
$$
\frac{1}{2}(m-1)(3 m-2)+1 \leqslant n \leqslant \frac{1}{2} m(3 m+1)
$$

then, $a_{n}=m$. Solving the inequality (2) for $m$, we get
$$
\frac{-1+\sqrt{24 n+1}}{6} \leqslant m \leqslant \frac{5+\sqrt{24 n-23}}{6} .
$$

The number of identical terms is $(3 m-1)$ for $m=1,2, \cdots$.
$$
\because 0<\frac{5+\sqrt{24 n-23}}{6}-\frac{-1+\sqrt{24 n+1}}{6}<1 \text {, }
$$
$\therefore m$ is the integer part of $\frac{1}{6}(5+\sqrt{24 n-23})$, denoted as $m=\left[\frac{5+\sqrt{24 n-23}}{6}\right]$.
Thus, $a_{n}=\left[\frac{5+\sqrt{24 n-23}}{6}\right]$.
Therefore, the sum of the first $n$ segments of the sequence $\left\{a_{n}\right\}$ is
$$
\begin{array}{l}
S_{n P 2}=1 \times 2+2 \times 5+3 \times 8+\cdots+n(3 n-1) \\
=3\left(1^{2}+2^{2}+\cdots+n^{2}\right)-(1+2+\cdots+n) \\
=3 \times \frac{1}{6} n(n+1)(2 n+1)-\frac{1}{2} n(n+1) \\
=n^{2}(n+1) .
\end{array}
$$

Substituting $n$ with $(m-1)$, we get the sum of the first $(m-1)$ segments as $S_{\frac{1}{2}(m-1)(3 m-2)}=m(m-1)^{2}$.
$$
\because a_{n}=m \text {, }
$$
$\therefore$ the sum of the first $n$ terms of the sequence $\left\{a_{n}\right\}$ is
$$
\begin{aligned}
S_{n} & =S_{\frac{1}{2}(m-1)(3 m-2)}+\left[n-\frac{1}{2}(m-1)(3 m-2)\right] m \\
= & m(m-1)^{2}+m n-\frac{1}{2} m(m-1)(3 m-2) \\
& =m n-\frac{1}{2} m^{2}(m-1), \\
\text { where } & m=\left[\frac{5+\sqrt{24 n-23}}{6}\right] .
\end{aligned}
$$

Note: From the above two examples, it can be seen that only by deeply understanding the dual role of $n$ in the sequence $\left\{a_{n}\right\}$, which is to determine the number of terms (or segments) and the elements, can such problems be correctly solved. The variable $n$ not only determines the elements of each term (or segment) in the summation but also decides the number of terms (or segments).